Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: On click, prevent mouseenter event

I have two seperate animations that are occurring, one fires on mouseenter the other on click. The problem is that when they are both activated it creates a jumpy animation.

You can see what I mean here: JSFiddle

Is it possible to prevent the mouseenter event from occurring if the click event is activated?

Javascript

$('header h1').mouseenter(function() {
  $('header:not(.open)').delay(500).animate({
    'padding-bottom': '40px'
  }, 150, function() {
    //function complete
  });
});

$('header h1').mouseleave(function() {
  $('header:not(.open)').animate({
    'padding-bottom': '20px'
  }, 150, function() {
    //function complete
  });
});

$('header h1').click(function() {

  if ($('header').hasClass('open')) {
    $('header p').fadeOut(100);
    $('header').removeClass('open').animate({
      'padding-bottom': '20px'
    }, 300, function() {
      //animation complete
    });
  }

  else {
    $('header').addClass('open').animate({
      'padding-bottom': '150px'
    }, 300, function() {
      $('header p').fadeIn();
    });
  }

});​
like image 586
colindunn Avatar asked May 28 '12 18:05

colindunn


2 Answers

Seems easier to just do this :

$('header').on({
    mouseenter: function(e) {
        if (!$(this).is('.open')) {
            $(this).stop(true, true).delay(500).animate({'padding-bottom': '40px' }, 150, function() {
                //function complete
            });
        }
    },
    mouseleave: function(e) {
        if (!$(this).is('.open')) {
            $(this).stop(true, true).animate({'padding-bottom': '20px'}, 150, function() {
            //function complete
            });
        }
    },
    click: function() {
        if ($(this).is('.open')) {
            $(this).find('p').fadeOut(100).end().removeClass('open').stop(true, true).animate({'padding-bottom': '20px'}, 300, function() {
                //animation complete
            });
        }else{
            $(this).addClass('open').stop(true, true).animate({'padding-bottom': '150px'}, 300, function() {
                $('p', this).fadeIn();
            });
        }
    }
});​
like image 91
adeneo Avatar answered Sep 24 '22 13:09

adeneo


No, you can't. Especially because those events are based on each other: To click on an element, you need to enter it with the mouse: You can't deactivate the enter event which already happened when you click. And you obviously shouldn't deactivate future click events when entering.

The solution to your problem with the jumping animations should be the stop() method, which ends running animations on the selected elements.

like image 33
Bergi Avatar answered Sep 25 '22 13:09

Bergi