Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 14:10
What would you like to do?
I'm having an issue with reassigning the Button to .second
<!DOCTYPE html>
<meta charset="utf-8">
<title>One Button Two Times</title>
<button class="first">ENTER</button>
<script src=""></script>
$(document).ready(function() {
$('.first').click(function() {
alert("made it to 1");
$('.second').click(function() {
alert("made it to 2");
Copy link

sfasano commented Nov 24, 2014

At the very bottom of this file, I'm trying to first use the button with class="first" and then remove the class "first", add class "second", and then have a separate interaction with this button the second time around.

Does anyone know what I'm doing wrong?

Copy link

This took me a few minutes to sort out but I think I got it :)

On line 24, you're adding the class of .second to your button, but by the time it finishes adding that class, it's already finished running line 27—right away. So basically, line 27 runs only once, and when it runs, nothing on the page has the .second class yet, so it's never called, and your code moves on.

To rephrase another way:

When your document loads, all your code runs, and everything that doesn't require an input happens right away. That includes line 27, except then (at the beginning) nothing has a class of .second yet, so it doesn't do anything. Some time later, you click on .first and it gets replaced with the new class .second but nothing tells line 27 to then run again, so nothing happens this time either :p

So the solution looks something like this:

$(document).on("click", ".second", function() { ... })—which says "also when people click, check for .second and if you find THAT, do this other thing".

So basically you'd have code then that on every click checked for .first, and more code that checked for .second and each has a different outcome.

Make sense?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment