Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with jquery animate()

I'm using this code to change opacity when user is on and off a picture unfortunately when the user clicks the image the opacity does not stay at 1. Anyone has an answer ?

$(document).ready(function(){

  $('img#slide').animate({"opacity" : .7})
  $('img#slide').hover(function(){
      $(this).stop().animate({"opacity" : 1})
  }, function(){
      $(this).stop().animate({"opacity" : .7})

  });                


  $('img#slide').click(function(){
    $(this).animate({"opacity" : 1});
  });

});
like image 865
andrei Avatar asked Jul 20 '26 18:07

andrei


1 Answers

You need to somehow disable the mouseleave animation when the user clicks.

A common approach is to add a class, and have the mouseleave check for the existence of the class.

Test the live example: http://jsfiddle.net/KnCmR/

$(document).ready(function () {

    $('img#slide').animate({ "opacity": .7 })

    .hover(function () {
        $(this).stop().animate({ "opacity": 1 })
    }, 
    function () {
        if ( !$(this).hasClass("active") ) {
            $(this).stop().animate({ "opacity": .7 });
        }
    })

    .click(function () {
        $(this).addClass("active");
    });
});

EDIT:

If you want a second click to revert the behavior back to the original, use toggleClass() instead of addClass():

        $(this).toggleClass("active");

jQuery docs:

  • .hasClass() - http://api.jquery.com/hasClass
  • .addClass() - http://api.jquery.com/addClass
  • .toggleClass() - http://api.jquery.com/toggleClass
like image 194
user113716 Avatar answered Jul 23 '26 08:07

user113716



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!