Help in jquery animate ()

I use this code to change the opacity when the user is on and off, unfortunately when the user clicks on the image, the opacity does not remain at 1. Does anyone have 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});
  });

});
+3
source share
3 answers

You need to somehow disable the animation mouseleavewhen the user clicks.

A common approach is to add a class and check mouseleavefor the existence of the class.

Check out 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 the second click to return the behavior back to the original, use toggleClass()instead addClass():

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

jQuery docs:

+2

, . , , , - . . . #slide , img#slide, a id :

$(document).ready(function(){
  var clicked = false;

  $('#slide')
    .animate({"opacity" : 0.7})
    .hover(function(){
      if(!clicked) {
        $(this).stop().animate({"opacity" : 1});
      }
    }, function(){
      if(!clicked){
        $(this).stop().animate({"opacity" : 0.7});
      }
    })
    .click(function(){
        clicked = true;
    });
});
+1

. .

, , . , :

$(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).unbind('hover');
  });
});

, -:

 $(document).ready(function(){

  var over = function(){
   $('img#slide').stop().animate({"opacity" : 1});
  };

  var out = function(){
   $('img#slide').stop().animate({"opacity" : 0.7});
  };

  var on = function(){
   $('img#slide').hover(over, out).one('click', off);
  }

  var off = function(){
   $('img#slide').unbind('hover').one('click', on);
  };

  $("img#slide").one('click', on);

  out.call();

 });

. ( ), .

0

Source: https://habr.com/ru/post/1750489/


All Articles