简体   繁体   中英

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);
    }
});

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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM