Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hover not triggered when element is programatically moved under the mouse

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)?

like image 362
travelboy Avatar asked Dec 09 '10 21:12

travelboy


People also ask

Is hover deprecated in jQuery?

hover() is deprecated #66.

Does jQuery handle hover?

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.

Which events are triggered by hover () method?

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.


2 Answers

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...
  }
});
like image 93
wajiw Avatar answered Nov 14 '22 22:11

wajiw


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.

like image 40
Ryan Avatar answered Nov 14 '22 23:11

Ryan