I have an image with a hover effect (higher opacity when mouse is over it). It works as desired when the mouse moves in and out.
However, the image itself is moving (I'm periodically changing the css attribute top). When the mouse does not move and the image moves under the mouse cursor, no related events are triggered. That means, the hover functions are not called. I also tried using the mouseenter and mouseleave events instead, but they don't work either.
What would be a good approach to get the desired behavior (hover effect whenever the mouse is over the image, regardless of why it got there)?
hover() is deprecated #66.
The hover() is an inbuilt method in jQuery which is used to specify two functions to start when mouse pointer move over the selected element.
The mouseover() method triggers the mouseover event, or attaches a function to run when a mouseover event occurs. Note: Unlike the mouseenter event, the mouseover event triggers if a mouse pointer enters any child elements as well as the selected element.
You won't be able to trigger mouse events if the mouse isn't moving, though you will be able to check where the mouse is when the image is moving. What you need to do is track the mouse position in a global variable, and check to see if that position is inside your image when it moves.
jQuery has a nice article about how to do it using their library: http://docs.jquery.com/Tutorials:Mouse_Position
To find the position of your image you can use the jQuery position function: http://api.jquery.com/position/
With that position you can create a bounds using the height/width of your image. On your image move check to see if that global mouse position is inside your image bounds and you should be good to go.
This is how I would write the code(completely untested btw):
var mousex = 0;
var mousey = 0;
jQuery(document).ready(function(){
$(document).mousemove(function(e){
mousex = e.pageX;
mousey = e.pageY;
});
})
img.move(function(){
...move code...
var p = $(this).position();
if(mousex >= p.left && mousex <= p.left + $(this).width
&& mousey <= p.top && mousey >= p.top + $(this).height)
{
...opacity code...
}
});
You could manually test to see if the mouse is in the image when you move the image then fire the desired event.
Mouse position using jQuery outside of events will show you how to keep track of the mouse position. Then just find the offset of the image and see if it's inside the image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With