Circle B
Circle B

Reputation: 1674

How to make jQuery click() function only run once

I have a scenario where I want an event to happen when a button is clicked, but then I want a different behavior when it's clicked the second time. Here's an example of what's happening:

$('.click').not('.clicked').click(function () {
    $(this).addClass('clicked');
    $('<p class="test">Test</p>').insertAfter(this);
});
.clicked {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' class="click" value="Click Me" />
<input type='button' class="click clicked" value="Click Me" />
<input type='button' class="click" value="Click Me" />

What I want it to do is stop running the jQuery once the class .clicked is added to the button. This works the way I would expect, if the button already has the class applied, but if I add the class with jQuery it doesn't stop running my function each time the button is clicked.

Upvotes: 1

Views: 117

Answers (1)

Diego
Diego

Reputation: 816

It does not matter which type of CSS selector you use because it will be executed only once. So you are adding an event listener for every tag with the class .click and without .clicked. You should do something like this:

$(document).on('click', '.click:not(.clicked)', function () {
    $(this).addClass('clicked');
    $('<p class="test">Test</p>').insertAfter(this);
});
.clicked {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' class="click" value="Click Me" />
<input type='button' class="click clicked" value="Click Me" />
<input type='button' class="click" value="Click Me" />

Adding the event listener to the whole document and later selecting the tags using .click:not(.clicked) allows you to "evaluate" the css selector every single time.

Upvotes: 4

Related Questions