0

I am changing my current class on the first click event and then I would like the class it was replaced with to have its own click event. Here is my current attempt:

$(".originalButton").on("click", function(){
  // THIS WORKS, it changes the class.
  $(this).closest(".questions").find(".originalButton").removeClass("originalButton").addClass("correctButton").off("click");
});

Now right under event handler I added this:

$(".correctButton").on("click", function(){
  debugger;

});

Ideally I would have something else instead of debugger, but at this point the event isn't even firing when the correctButton class button is clicked, even though when I inspect element the class updated properly (from the first click event).

1 Answer 1

2

You need to use event delegation as you are adding/removing classes dynamically . Use:

$(".questions").on("click",'.correctButton', function(){
   debugger;
});
Sign up to request clarification or add additional context in comments.

5 Comments

He should bind ".originalButton" with delegation, too. If not, the second time both events will be fired.
@Johnny5: not sure whether OP needs that. also OP is removing the click event when adding newClass
not exactly the body tag, he can just use the immediate parent of .correctButton
@Zafarbek: yes...may be element with class questions
of course if he have a selector for the parent. but either ways work good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.