Jerry Svensson Jerry Svensson - 5 months ago 31
jQuery Question

Make .click assigned to several same classes work only on clicked element

I need to assign a class and toggle an element on .click. Problem is that I have several element with the same class - and the click will open all of the sub-containers, where I only want to open the container in the element where the click is. I have managed to set the class for just the child of the clicked element, but I cant make the toggle work. What Am I doing wrong?

Fiddle: http://codepen.io/anon/pen/VjevRY

HTML:

<div class="container">
<a class="click">click me</a>
<div class="sub-container"></div>
</div>

<div class="container">
<a class="click">click me</a>
<div class="sub-container"></div>
</div>

<div class="container">
<a class="click">click me</a>
<div class="sub-container"></div>
</div>

<div class="container">
<a class="click">click me</a>
<div class="sub-container"></div>
</div>


Script:

$('a.click').click(function() {
$(this).closest('.container a.click').toggleClass('open');
$(this).closest('.container .sub-container').slideToggle(600);
});

Answer

$("a.click").click(function() {
  $(this).toggleClass('open');//use $(this)
  $(this).next(".sub-container").slideToggle(600);//use $(this) and .next()
})
.sub-container {
    width: 300px;
    height: 300px;
    background: black;
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <a class="click">click me</a>
  <div class="sub-container"></div>
</div>

<div class="container">
  <a class="click">click me</a>
  <div class="sub-container"></div>
</div>

<div class="container">
  <a class="click">click me</a>
  <div class="sub-container"></div>
</div>

<div class="container">
  <a class="click">click me</a>
  <div class="sub-container"></div>
</div>
Script:

  1. Use $(this) to get the clicked element
  2. Use .next() to get the container of the clicked element
Comments