Search code examples
jqueryanimationopacity

Opacity Loop in jQuery


I have two images in a stack, say #a and #b. b's opacity is 1 and I want when I hover my mouse over it, it will start animating opacity from 0 to 1 and than 1 to 0. In this way this loop will be continued until mouse goes out of the image.

You can find a similar thing here: http://www.myhabit.com/#page=b&dept=women&sale=A3RT7N8JLFHTE3&ref=qd_g_cur_img_b

I am new in jQuery.


Solution

  • var cancel = false;
    
    $("#b").hover(function() {
        var fadeDirection = 0;
    
        var next = function(jqo) {
            if(cancel) {
                jqo.stop(true);
                jqo.fadeIn(); // <-- not the neatest but I don't know another way to make it compatible
                jqo.stop(false, true);
            }
    
            if(fadeDirection = 1 - fadeDirection) {
                jqo.fadeIn(function() { next(jqo); });
            } else {
                jqo.fadeOut(function() { next(jqo); });
            }
        };
    
        next($(this));
    }, function() {
        cancel = true;
    });
    

    Something like that?