JohnG
JohnG

Reputation: 497

JQuery toggling button not working

I'm trying to find an easy alternative to the deprecated toggle() method in jQuery. I want to make an element slide at the click of a button, and slide the other way when you click the same button again. I thought a simple solution would be to give the button a class of "first", and then have my jQuery as:

$(document).ready(function(){
    $(".first").click(function(){
        $(this).removeClass("first");
        $("#slider").removeClass("slideout");
        $("#slider").addClass("slidein");   
        $(this).addClass("second");
    });
    $(".second").click(function(){
        $(this).removeClass("second");
        $("#slider").removeClass("slidein");
        $("#slider").addClass("slideout");  
        $(this).addClass("first");
    });
});

It doesn't work though. On the initial click slidein executes, and the button's class changes to "second" when I inspect the element, but the second click does nothing. If I apply "second" to a different object though, the slideout works fine. (Oddly, I can then click on my original button again and slidein works once more - and back and forth - even though the button no longer has the class "first"). Am I missing something?

Upvotes: 0

Views: 151

Answers (1)

SSA
SSA

Reputation: 5483

Use $(document).on('click', ".second", function() { as second class is added dynamically.

Upvotes: 1

Related Questions