jasmine
jasmine

Reputation:

Stop fadeTo() in jquery

I used

$(document).ready(function() {

$("#main ul li").hover(function(){

var fade = $('img.g-img', this);
fade.fadeTo('slow', 0.5);


$("#main ul li").removeClass("active");
$(this).toggleClass("active");

});


}); 

I want to stop fade, when mouseout. This code not working:

fade.stop().fadeTo('slow',1)

How can I do this? Thanks in advance.

Upvotes: 3

Views: 4094

Answers (2)

SLaks
SLaks

Reputation: 887453

You need to pass two parameters to hover. (A mouseenter handler and a mouseleave handler)

For example:

$(document).ready(function() {
    $("#main ul li").hover(
        function() { //mouseenter handler
            var fade = $('img.g-img', this);
            fade.fadeTo('slow', 0.5);

            $("#main ul li").removeClass("active");
            $(this).toggleClass("active");
        }, 
        function () {  //mouseleave handler
            var fade = $('img.g-img', this);
            fade.stop().fadeTo('slow',1)
        }
    );
});

Upvotes: 3

cletus
cletus

Reputation: 625087

The fade variable you are defining is only in scope within the event handler. Plus you need two event handlers for hover(): one for when the mouse enters and another for when it leaves.

$(document).ready(function() {
  $("#main ul li").hover(function() {
    $(this).addClass("active").find("img.g-img").stop().fadeTo("slow", 0.5);
  }, function() {
    $(this).removeclass("active").find("img.g-img").stop().fadeTo("slow", 1);
  });
});

Upvotes: 2

Related Questions