0

HTML:

<a class="myAnchor">asd1<img class="imagenmangue" alt="" src="/images/asd1.jpg" height="215" width="430""></a>

css:

a.myAnchor img{visibility:hidden}
a.myAnchor:hover img{visibility:visible}

Script:

/*  move the image  */
$('.myAnchor').hover(function(){     
  $(document).on( "mousemove", function( event ) {
  if ($( document ).width() > 800) {
     $(".imagenmangue").css({left: (event.pageX - $('.tabs_type_2').offset().left + 15),top: (event.pageY - $('.tabs_type_2').offset().top - 35)});
  }  else {
 };
});
}, function(){      
});

I´m doing this so the image moves with the mouse, when it is on the a:hover. But the browser goes slowly. How can i solve this?

4
  • 3
    What you're looking for is throttle and/or debounce.
    – Brad
    Jul 29, 2014 at 13:38
  • I'm looking for both, but mostly the debounce!
    – Francisco
    Jul 29, 2014 at 13:41
  • @user3704434 have you tried using that yourself? Jul 29, 2014 at 13:43
  • yes, I've tried. But I'm really new on this and i don't understand to much.
    – Francisco
    Jul 29, 2014 at 13:55

2 Answers 2

1

Every time you hover over the element you are adding a new event listener to the document! You are overloading the mousemove. You want to only add one mousemove event. Either remove the event when done or add the event once and set a flag when you want it to run.

2
  • Thank you! I am learning and do not understand much of this, how can I do any of those two things? Remove the event or use a flag?
    – Francisco
    Jul 29, 2014 at 13:52
  • @Francisco you can use a flag, or set the element once on the document ready event: $(document).ready(function(){/*Set mousemove event handler here*/}); Jul 29, 2014 at 13:57
0

As pointed out by user epascarello, you can attach the event listener once to the element itself, rather than to add a new one to the document every time you hover .myAnchor. So instead of declaring it like this:

/* Every time .myAnchor gets hovered */
$('.myAnchor').hover(function(){     
    /* Create a new event listener that listens to the mouse movements inside the document */
    $(document).on( "mousemove", function( event ) {
        /* do stuff here */
    });
});

You can declare it like this:

/* When the mouse moves over .myAnchor */
$(document).on( "mousemove", ".myAnchor", function( event ) { 
    /* do stuff here */
}

I've created a JSFiddle with more a more in-depth explanation of what's going on in your code, you can check it out here: http://jsfiddle.net/M7bWS/

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.