Search code examples
javascriptjquerytogglebutton

Use fadeIn when attribute has changed


When I click on the toggle button, it changes the style attribute of the element from display none to block. Now, when this happens, I want to animate the left position of the menu. I have code like this, but works buggy and also, when it should go back to the right, it appears on the left..

var toggled = false;
$(toggleBtn).click(function() {
    toggled = !toggled;
    $(collapse).attr("style", toggled ? 'display:block !important' : 'display:none !important');
    if (collapse.attr('style', 'display:block !important')) {
        $(collapse).animate({left:'10%'});
    } else {
        $(collapse).animate({left:'100%'});
    }
});

Any help would be appreciated, thank you.


Solution

  • You can simplify this more as:

    var toggled = false;
    $(toggleBtn).click(function() {
        toggled = !toggled;
        $(collapse).toggle(toggled)
                   .animate({ left: $(collapse).is(':visible') ? '10%' : '100%' });
    });