Avery Lucas Avery Lucas - 4 months ago 9
Javascript Question

Changing button classes dynamically not working

<button class="changeMe"> Click Me </button>




$(".changeMe").on("click", function(){
console.log("I should only work the first time!")
$("changeMe").addClass("secondClass").removeClass("changeMe");
});

$(".secondClass").on("click", function(){
console.log("Now I should Work!")
});


This is basically what my code looks like.

I click the button.
Chrome developer tools show that the class was removed.
I click the button again, and the same bit of jquery code runs even thou the class its pointing too dosnt exist.

How do I stop that from happening.

EDIT:: Ooopss forgot the dot. I have the dot in my solution. This is just for demonstration purposes. Added dot.

Answer

1) Add . before class name, so it will be $(".changeMe") and $(".secondClass")

2) Use $(document).on("click") event

Try:

$(document).on("click",".changeMe", function(){
    console.log("I should only work the first time!")
    $(".changeMe").addClass("secondClass")
    $(".changeMe").removeClass("changeMe");
});

$(document).on("click",".secondClass", function(){
    console.log("Now I should Work!")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button class="changeMe"> Click Me </button>