Search code examples
jqueryanimationjquery-effects

jQuery switchClass


Is it possible to undo a switchClass transition?

I'd like an element to slowly obtain class A as you hover over it, and slowly lose it again once the mouse has moved away. However, the function appears to be glitchy, and calling .stop(0,1) doesn't seem to help. In fact, it seems to break it.

I have a live example here. Yes, it's a 404 page, but that's not important. The navigation should be slowly gaining or losing a class, but it just jumps. The script can be found here.

Is such a transition possible?

EDIT:

Here's the code I'm using:

$('#navbar li:not(.current) a').hover(function() {
    $(this).parent()
        .stop(1,0)
        .addClass('current', 1000);
}, function () {
    $(this).parent()
        .stop(1,0)
        .removeClass('current', 1000);
});

Is it perhaps because changing the class of the li doesn't result in the style of its children being transitioned?

EDIT2:

Yup, that 'fixed' it. The true bug can now be observed in all its glory (getting frozen in an intermediate state).


Solution

  • This is the closest I've come to making it work:

    Example: http://jsfiddle.net/TUrvP/

    There may be some overkill, and you may be able to use the :animated selector, though I had troubles at first.

    May not be worth the effort...

    HTML

    <div id='myElement' class='blue'>content</div>
    

    CSS

    div {
        width: 100px;
        height: 100px;
    }
    
    .blue {
        background: blue;
        position:relative;
        left: 20px;
    }
    .myClass {
        background:red;
        margin-top: 50px;
    }
    

    jQuery

    var animating = false;
    var interval;
    $('#myElement').hover(
        function() {
            var $th = $(this);
            if(!animating && !interval) {
                $th.clearQueue();
                animating = true;
                $th.addClass('myClass',500,function() {animating=false;});
            }
        },
        function() {
                var $th = $(this);
                if(interval) return false;
                if(animating) {
                    interval = setInterval(function() {
                                                if(!animating) {
                                                    $th.clearQueue();
                                                    animating = true;
                                                    $th.removeClass('myClass',500, function(){animating = false;});
                                                    clearInterval(interval);
                                                    interval = null;
                                                }},50)
                } else {
                    $th.clearQueue();
                    $th.removeClass('myClass',500, function(){animating = false;});
                }
            }
    );