I have a deferred function that binds a mouseenter event:
$(window).load(function(e) {
var $container = $('.container');
$container.mouseenter(function(e) {
//do something
});
...
});
The problem is the mouse might already be over the element when the load event fires, hence before the mouseenter event was bound.
I can get around this by putting some code at the end of the page load handler to do a one-time check if the mouse is inside the element and trigger the mouseenter event manually:
// check if the mouse is inside $container
if(mouse is inside $container)
$container.mouseenter();
How can I check if the mouse is over the element in the load event?
I tried $container.is(':hover')
but it doesn't work.
Mouseover event does exactly what you want.
If the
.conteiner
does not exist in time you attach the mouseover event (is added dynamically in the future) you have to use .live method to attach the event.It will work also when the mouse is already on the position, where the new element appears. Example here!
For jQuery 1.7+ you should use .on method instead as the .live method is deprecated. Example here!
Best way to do this is to get the left, right, top, and bottom offset of the element and see if the mouse position lies anywhere between those values.
Example.
Put your mouse over the div the first time it loads. Then refresh the page (click F5 so you don't have to move the mouse). When the page loads fully next time, it should alert with "Hover!" even if you haven't moved your mouse.
Or an even easier way. Just check the
e.target.id
of the mousemove event (which apparently fires once the page loads, even without moving the mouse) against theid
of the element, like so:Example (do the same steps as above).
I went with the css hover solution in Detect mouse hover on page load with jQuery because it doesn't require the mousemove event.
With jQuery 1.7+ you're going to want to use
.on()
: http://api.jquery.com/on/.live is deprecated. You could also put any other events in .on as well, depending on what you need. :hover doesn't work because it only works with specific elements and it's css based.
Using this in conjunction with an offset detection approach for before the page finishes loading will get you where you want to be.
i dont test it yet but think you want like this...