JQuery UI bounce effect - bounce only once on entering div

Kate R picture Kate R · Jun 21, 2012 · Viewed 7.9k times · Source

I have a div that I want to bounce once, when the mouse enters/hovers over the div.

The code I have works in Chrome, but not in Firefox or IE.

http://jsfiddle.net/d7UjD/73/

In Chrome it bounces once as desired but in FF and IE the bouncing goes on as long as the mouse remains in place.

I also tried $('#box').one("mouseenter", function() { but the box bounces once, and subsequent entries into the div do not trigger the effect.

Any thoughts on why the browsers are behaving differently and what I can do about it?

Answer

Roko C. Buljan picture Roko C. Buljan · Jun 21, 2012

LIVE DEMO

$("#box").hover(function(){
if ( !$(this).data("bouncing") ){
      $(this).effect("bounce", { direction: 'up', distance: 10, times: 1 })
             .data("bouncing", true);
}
},function () {
     $(this).data("bouncing", false);
});

Once it bounces, the element data attribute will hold the true boolean,
inside the if statement we just check for it's true or false.
On mouse-leave we just set it to false, to allow a new hover and a... new bounce! :)

You can also write the above like:

$("#box").on('mouseenter mouseleave',function( e ) {
  var el = $(this);
  if(!el.data("b"))el.effect("bounce", {direction:'up',distance:10,times:1} );
  el.data("b",e.type=="mouseenter"?true:false);
});