简体   繁体   中英

Problem with jquery fadeIn() fadeOut() animation

I'm creating a filterable gallery so the user can select the category and the gallery will show the images only of that category.

I want to change the image on hover and this was very simple. Now I'm trying to add animation for changing the image so I want that the old image will fadeOut and then change the image and after changing the image fadeIn.

I have also achieved that but there is an error that I'm unable to figure out. This works fine for only the first time then the animation executes one more time. For example when I hover the second time the animation works 2 times and if I hover a 4th time the animation work 4 times.

$('.product_image').mouseenter(function() {
  $(this).fadeOut('fast', function() {  
    $(this).attr('src', 'www.mydomain.com/img/default.jpg').fadeIn();
  });

  $('.product_image').mouseleave(function() {
    $(this).fadeOut('fast', function() { 
      $(this).attr('src', 'realimage').fadeIn();
    });

The issue is because the mouseleave event is nested within the mouseenter , so you're adding a new event handler each time.

To fix this, separate the event handlers:

$('.product_image').mouseenter(function() {
  $(this).fadeOut('fast', function() {
    $(this).attr('src', 'www.mydomain.com/img/default.jpg').fadeIn();
  });
});

$('.product_image').mouseleave(function() {
  $(this).fadeOut('fast', function() {
    $(this).attr('src', 'realimage').fadeIn();
  });
});

Note that you can also make this a little more succinct by using on() from a single jQuery object:

$('.product_image').on({
  mouseenter: function() {
    $(this).fadeOut('fast', function() {
      $(this).attr('src', 'www.mydomain.com/img/default.jpg').fadeIn();
    });
  },
  mouseleave(function() {
    $(this).fadeOut('fast', function() {
      $(this).attr('src', 'realimage').fadeIn();
    });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM