Sam Jones Sam Jones - 25 days ago 14
jQuery Question

using .one() on multiple classes

I have multiple divs with the same class name, but once one is clicked I don't want my function to happen again if another with the same class is clicked again.

$('.js-item').one( "click", function() {
console.log('clicked once');
// do something only once even if a div with the same class is clicked again
});


Is there a way for .one() to happen only once on all my classes? Because at the moment it applies just once but each time an individual div with that class name is clicked.

I need these divs to have the same class name.

Answer

You can call off() on all those classes after executing your logic:

$('.js-item').one("click", function() {
  console.log('clicked once');

  // do something only once even if a div with the same class is clicked again

  $('.js-item').off('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="js-item">click me!</div>
<div class="js-item">click me!</div>
<div class="js-item">click me!</div>
<div class="js-item">click me!</div>
<div class="js-item">click me!</div>

Using this method makes the one() redundant, so you can revert back to the standard on() if you prefer.

Comments