Reece
Reece

Reputation: 2711

Prevent event firing if element has a certain class

I have created an ajax load more button that when clicked gets more posts. When the button is clicked a class of loading is added to it and then later removed when all the content has been output.

Is it possible to use the jQuery :not selector to stop the click event firing if the button has a class of loading?

Here's a short demo

jQuery('#test_btn:not(.clicked)').click(function(){
    jQuery(this).addClass('clicked');
    console.log('hi');
});

<div id="test_btn">test<br>button</div>

Is this not how you use the :not selector? because I am able to fire the click event even when the class of loading is added to it.

Upvotes: 1

Views: 97

Answers (2)

Jamiec
Jamiec

Reputation: 136174

The problem is that using that method of attaching a click event only runs on page load. It never updates.

You should use this:

$(document).on('click','#test_btn:not(.clicked)',function(){
   jQuery(this).addClass('clicked');
    console.log('hi');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="test_btn">Click - only works once</button>

When you come along later (say, when the ajax call has loaded) and remove the loading class from the button, the event will once again work

$(document).on('click','#test_btn:not(.clicked)',function(){
   jQuery(this).addClass('clicked');
    console.log('hi');
});

$(document).on('click','#reset',function(){
   jQuery('#test_btn').removeClass('clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="test_btn">Click - only works once</button>
<button id="reset">Click to reset</button>

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337714

As you are dynamically adding the class you need to use a delegated event handler in order for the :not() selector to be respected:

$(document).on('click', '#test_btn:not(.clicked)', function() {
  $(this).addClass('clicked');
  console.log('hi');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test_btn">test<br>button</div>

Alternatively if the sole point of this logic is to only allow the element to be clicked once, just use one():

$('#test_btn:not(.clicked)').one('click', function() {
  $(this).addClass('clicked');
  console.log('hi');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test_btn">test<br>button</div>

Upvotes: 2

Related Questions