Chris Mazzochi Chris Mazzochi - 1 month ago 5
Javascript Question

jQuery On Click Requiring Two Clicks After The First

I have looked at similar questions and read the proposed solutions, but it seems each case regarding this issue is different.

Very simply when I press my menu icon the first time, my slideout menu appears. Each time after the first requires two presses or two clicks to activate the slideout menu.

The jQuery -

$('.slideout-menu-toggle').on('click', function(event){
event.preventDefault();

// create menu variables
var slideoutMenu = $('.slideout-menu');
var slideoutMenuWidth = $('.slideout-menu').width();

// toggle open class
slideoutMenu.toggleClass("open");

// slide menu
if (slideoutMenu.hasClass("open")) {
slideoutMenu.animate({
left: "0px"
});
} else {
slideoutMenu.animate({
left: -slideoutMenuWidth
}, 250);
}
});


$('.slideout-menu-close').on('click', function(event){
event.preventDefault();
// create menu variables
var slideoutMenu = $('.slideout-menu');
var slideoutMenuWidth = $('.slideout-menu').width();

// toggle open class
slideoutMenu.toggleClass("open");

// slide menu
if (slideoutMenu.hasClass("open")) {

slideoutMenu.animate({
left: -slideoutMenuWidth
}, 250);

} else {
slideoutMenu.animate({
left: "0px"
});
}

});


You can see a demo of the problem viewing through a smartphone at www.chrismazzochi.com.

Thanks for you help,
Chris

Answer

You are facing this problem because you toggle class before checking for class "open" using hasClass(). Just toggle class "open" after condition check.

Try this :

$('.slideout-menu-toggle').on('click', function (event) {
        event.preventDefault();
        // create menu variables
        var slideoutMenu = $('.slideout-menu');
        var slideoutMenuWidth = $('.slideout-menu').width();

        // toggle open class
        slideoutMenu.toggleClass("open");

        // slide menu
        if (slideoutMenu.hasClass("open")) {
            slideoutMenu.animate({
                left: "0px"
            });
        } else {
            slideoutMenu.animate({
                left: -slideoutMenuWidth
            }, 250);
        }
    });


    $('.slideout-menu-close').on('click', function (event) {
        event.preventDefault();
        // create menu variables
        var slideoutMenu = $('.slideout-menu');
        var slideoutMenuWidth = $('.slideout-menu').width();

        // toggle open class
        if (slideoutMenu.hasClass("open")) {

            slideoutMenu.animate({
                left: -slideoutMenuWidth
            }, 250);

        } else {
            slideoutMenu.animate({
                left: "0px"
            });
        }
        // toogle class after condition check
        slideoutMenu.toggleClass("open");
    });