Question

My current code is too messy. Could you please help make it more efficient.

function buttons(){
    $('.notclicked').click(function(){
        $('.leftmenu').addClass('leftclicked');
        $('.mainwrap').addClass('mainclicked');
        $(this).removeClass('notclicked');
        $(this).addClass('clicked');
        $('.clicked').click(function(){
            $('.leftmenu').removeClass('leftclicked');
            $('.mainwrap').removeClass('mainclicked');
            $(this).removeClass('clicked');
            $(this).addClass('notclicked');
            buttons();
        });
        buttons();
   });
};
buttons();

As seen here. (http://quinnkeaveney.com/recondite/brian/index.php)

Was it helpful?

Solution

You can use

$(document).on('click', selector, function() {
  // your function
}

to bind clicks to selectors that may not have loaded yet.

OTHER TIPS

$('#menu').click(function(){
    var btn = $(this);
    // find out if it has the notclicked class
    var notClicked = btn.hasClass('notclicked');
    // when notClicked is true, toggleClass acts like addClass
    // when notClicked is false, toggleClass acts like removeClass
    $('.leftmenu').toggleClass('leftclicked', notClicked);
    $('.mainwrap').toggleClass('mainclicked', notClicked);
    // This will toggle these both back and forth
    btn.toggleClass('notclicked clicked');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top