Alexander Hein Alexander Hein - 7 months ago 18
Javascript Question

Run function for each element separately?

How do I run a function for each element separately?

So if I click on the first

open
only the first group should open.



$(document).on('click', "a.showdetails", function () {
$( ".group" ).toggleClass( "opened" );
});

.option{
width: 200px;
}

.showdetails{
display: block;
}

.group{
display: none;
width: 200px;
height: 100px;
background: #f2f2f2;
}

.group.opened{
display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="option">
<a href="#" class="showdetails">open</a>
<div class="group"></div>
</div>

<div class="option">
<a href="#" class="showdetails">open</a>
<div class="group"></div>
</div>




Answer

You need to use clicked element context to find its sibling element with class group:

var groupelements = $('.group');
$(document).on('click', "a.showdetails", function () {
  var targetgroup = $(this).next('.group');
  groupelements.filter(targetgroup).removeClass( "opened" )
  targetgroup.toggleClass( "opened" );
});

NOTE: You have used event delegation here. You should only use it if elements a.showdetails are loading dynamically. else use .click to bind the click for static element.