1

I use jQuery .animate() to move an item once, but it seems to be moving in increments of 100px multiple times. Is it because of mouseover over?

var ww = $(window).width();

$(document).on('mouseover', '#myTarget', function () {
     var dp = $(this).offset().left;

     if ((ww - dp) < 150) {
         $('.myDiv.active').animate({left:'-=100px'},500);
     }
}); 
santa
  • 12,234
  • 49
  • 155
  • 255

3 Answers3

1

The mouseover event is sent repeatedly while the mouse is over the target. You may want mouseenter and mouseleave

Steve H.
  • 6,912
  • 2
  • 30
  • 49
1

Use jquery.one

$(document).one('mouseover', '#myTarget', function () {
  var dp = $(this).offset().left;

  if ((ww - dp) < 150) {
     $('.myDiv.active').animate({left:'-=100px'},500);
  }
}); 
jonathanGB
  • 1,500
  • 2
  • 16
  • 28
  • .one() is neat, but I need to be able to call this function again, so in this particular case mouseenter may save the day. Thanks for recommending .one(), I've never used it but it has great potential. – santa Oct 05 '16 at 18:11
  • Ok great, misunderstood your question – jonathanGB Oct 05 '16 at 18:13
1

Changing it to $(document).on('mouseenter', '#myTarget', function () { would be better. Every time your mouse enters or leaves the element or one of its children, a mouseover event is triggered. This will not happen with mouseenter. The example here shows this.

See this answer for a similar question and the source for the example provided.

Community
  • 1
  • 1
Nick G
  • 1,953
  • 12
  • 16