Toggle instead of Hover function jQuery

I want to repeat the same process everytime I click on the class specified in the code. It was working on hover function but when I switched to click function, it does the job one time only. and it's not repeatable.

Also I switched to clickToggle and it does not work. Any thoughts?

var sidebarFloat = $('.sidebar').css('float');
$('.sidebar').hover(function() {
    sidebarFloat = $(this).css('float');

    if (sidebarFloat == 'right') {
        $(this).stop().animate({
            left: "0px"
        }, 500)
    } else if (sidebarFloat == 'left') {
        $(this).stop().animate({
            left: "0px"
        }, 500)
    }
}, function() {
    var width = $(this).width() - 10;
    if (sidebarFloat == 'right') {
        $(this).stop().animate({
            left: +width
        }, 500);

    } else if (sidebarFloat == 'left') {
        $(this).stop().animate({
            left: -width
        }, 500);
    }
});

Answers 1

  • The jquery hover() function takes two functions as parameters: handleIn and HandleOut.

    Click does not.

    As a result you will have to track the state of the click using a separate variable.

    For example:

    var sidebarFloat = $('.sidebar').css('float');
    var toggled = false;
    $('.sidebar').click(function() {
        if (toggled) {
            sidebarFloat = $(this).css('float');
            if (sidebarFloat == 'right') {
                $(this).stop().animate({
                    left: "0px"
                }, 500)
            } else if (sidebarFloat == 'left') {
                $(this).stop().animate({
                    left: "0px"
                }, 500)
            }
        } else {
            var width = $(this).width() - 10;
            if (sidebarFloat == 'right') {
                $(this).stop().animate({
                    left: +width
                }, 500);
    
            } else if (sidebarFloat == 'left') {
                $(this).stop().animate({
                    left: -width
                }, 500);
            }
        }
        toggled = !toggled;
    });
    

Related Articles