DevJoe
DevJoe

Reputation: 443

Toggle same class for the specific item that's being clicked

I have a class, let's call it 'toggle-something' which is defined in CSS, and I would like to apply that class to every item that's being clicked. Question is how could I shorten this code so there's only one click function which would handle all items..?

$('.first').on('click', function() {
     $('.item-first').toggleClass('toggle-something');
});

$('.second').on('click', function() {
     $('.item-second').toggleClass('toggle-something');
});

<button class="first">
  <div class="item-first">
    lorem
  </div>
</button>

<button class="second">
  <div class="item-second">
    ipsum
  </div>
</button>

.toggle-something {color: red;}

Upvotes: 1

Views: 592

Answers (4)

palaѕн
palaѕн

Reputation: 73906

You can do this like:

$('button').on('click', function() {
  $(this).find('div').toggleClass('toggle-something');
});
.toggle-something {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="first">
  <div class="item-first">
    lorem
  </div>
</button>

<button class="second">
  <div class="item-second">
    ipsum
  </div>
</button>

Upvotes: 1

Jonathan
Jonathan

Reputation: 724

I would do this if you want to select which elements that should be able to call the function:

JS

$('.click').on('click', function() {
     $(this).toggleClass('toggle-something');
});

HTML

<button class="first">
  <div class="item-first click">
    lorem
  </div>
</button>

<button class="second">
  <div class="item-second click">
    ipsum
  </div>
</button>

Basically what is done is that you add the class click to every element that should be able to start the toggle function.

If you want everything to be able to toggle, then refer to @RenzoCC answer!

Upvotes: 1

Renzo Calla
Renzo Calla

Reputation: 7696

You can use the * generic selector...

$('*').on('click', function(e) {
  e.stopPropagation();
     $(this).toggleClass('toggle-something');
});
.toggle-something{
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>a</div>
<span>a</span>
<p>a</p>

Upvotes: 2

Titus
Titus

Reputation: 22474

You can reference the clicked item using $(this) which means that you can do something like this:

$('.first, .second').on('click', function() {
     $(this).find("div").toggleClass('toggle-something');
});

Upvotes: 1

Related Questions