Kenneth Ma
Kenneth Ma

Reputation: 77

jquery fadeIn and fadeOut not working

So I have 3 images in place where when the user clicks on it, it changes to another image. But I wanted to add a jQuery fadeOut and fadeIn to give a transition effect of the switching process. This is what I've came up with but it's not working, any idea?

$(".chosen").click(function() {     
    var src = $(this).attr("src");      
    if (src == "blank.png") (function() {
        $(this).fadeOut(400);
        {
            $(this).attr("src", "ex.png").fadeIn(400);      
        }
    });

    else if (src == "ex.png") (function() {
        $(this).fadeOut(400);
        {
            $(this).attr("src", "oh.png").fadeIn(400);          
        }
    });

    else (function() {
        {
            $(this).fadeOut(400);
            $(this).attr("src", "blank.png").fadeIn(400);       
        }
    });
});

Upvotes: 0

Views: 139

Answers (1)

Matthew
Matthew

Reputation: 25743

You should change the source of the image and transition back in after the fadeOut animation completes.

The fadeOut documentation shows a complete parameter for a callback when the animation is done rendering.

$(this).fadeOut(400, function(){/*code to be executed when animation finishes*/});

In your example, you can do:

$(this).fadeOut(400, function(){
    $(this).attr("src", "ex.png").fadeIn(400); 
});

You can refactor you code to reduce redundant code like so:

$(".chosen").click(function() {     
    var $this = $(this); // avoid calling $ multiple times

    $this.fadeOut(400, function() {
        var src = $this.attr("src");    
        var newSrc = "";

        // this if/else block could be refactored further
        if (src == "blank.png") {
            newSrc = "ex.png";
        }
        else if (src == "ex.png") {
            newSrc = "oh.png";
        }
        else { // if src == "oh.png"
            newSrc = "blank.png";
        }

        $this.attr("src", newSrc).fadeIn(400);
    });
});

Upvotes: 1

Related Questions