a7omiton
a7omiton

Reputation: 1617

how to stop rapid hover events in jQuery

I want to add buttons to my carousel that show up when the user is hovered over the carousel and hide them when they leave that element.

I've done that, but when I rapidly enter and leave the element being hovered, the animation (opacity 0-1) happens repeatedly once I stop.

Here is a fiddle to demonstrate. You have to quickly enter and leave the result box to see what I mean (the black flashly things are a representation of my buttons)

http://jsfiddle.net/BrshS/

transitions the opacity on hover, but repeats it a lot when hovered many times

anybody know how i can stop this from happening? much appreciated, been at it for hours (i.e. almost the whole day :/)

Upvotes: 0

Views: 130

Answers (3)

Kevin B
Kevin B

Reputation: 95031

you can "stop" it with the stop method,

x.stop(true,true).animate(

http://jsfiddle.net/Tentonaxe/BrshS/4/

or maybe even the finish method.

x.finish().animate(

http://jsfiddle.net/Tentonaxe/BrshS/5/

Upvotes: 0

nietonfir
nietonfir

Reputation: 4881

Updated your example to use CSS3 animations as that's the way to go nowadays. No javascript needed, better performance and graceful degradation for free!

.next,
.prev {
    opacity: 0;
    transition: opacity .25s ease-in-out;
    -moz-transition: opacity .25s ease-in-out;
    -webkit-transition: opacity .25s ease-in-out;
}

.image_carousel:hover .next,
.image_carousel:hover .prev {
    opacity: 1;
}

Upvotes: 2

ahren
ahren

Reputation: 16961

You can simply use .fadeTo() instead of the animation method, as well as .stop() to interrupt the current animation.

  var $buttons = $('#next, #prev').hide();

  $('.image_carousel').hover(function() {
    $buttons.stop().fadeTo(300,1);
  },
  function(){
    $buttons.stop().fadeTo(300,0);
  });

Demo: http://jsfiddle.net/BrshS/2/

Upvotes: 1

Related Questions