简体   繁体   中英

On first click animation works good, on second it skips some steps

For this animation I use velocity.js and here is the code

$(document).ready(function() {
    $('.shrink').on('click', function() {
        $(".spread").removeClass("spread").addClass("shrink");
        $(this).removeClass("shrink").addClass("spread");
        $(".spread").velocity({
            width: "80%"
        }, 300);
        $(".shrink").velocity({
            width: "5%"
        }, 300);
        $('.spread').on('click', function() {
            $(this).removeClass("spread").addClass("shrink");
            $(".shrink").velocity({
                width: "20%"
            }, 300);
        });
    });
});

and the jsfiddle with full animation preview.

So, when you click on some column it opens and click again it closes. That is how it is supposed to work. But, the problem is if you now click again on the same column, it will open and close immediately, which is not the effect I want.

How can I fix this?

Btw, not sure why, but currently is not working in chrome, but it works in ff.

Learn about event delegation

simple rewrite of your code becomes

$(document).ready(function () {

    $('body').on('click', '.spread', function () {
        $(this).removeClass("spread").addClass("shrink");
        $(".shrink").velocity({
            width: "20%"
        }, 300);
    });
    $('body').on('click', '.shrink', function () {

        $(".spread").removeClass("spread").addClass("shrink");

        $(this).removeClass("shrink").addClass("spread");

        $(".spread").velocity({
            width: "80%"
        }, 300);

        $(".shrink").velocity({
            width: "5%"
        }, 300);


    });

});

DEMO

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