Reputation: 539
So, I'm struggling here. I want to make an on click even that when I click on a navigation, it opens nested list and add class to parent list. That part almost works, problem is that it adds that class to all elements from parent list.
<ul>
<li><div><p class="hidden">Test 1</p>
<ul class="shown">
<li>
<a href="#"><p>Inner 1</p></a>
</li>
</ul>
</div>
</li>
<li><div><p class="hidden">Test 2</p>
<ul class="shown">
<li>
<a href="#"><p>Inner 2</p></a>
</li>
</ul>
</div>
</li>
</ul>
<ul>
jque
$(document).ready(function () {
$('.shown').hide();
$('.hidden').click(function () {
var $answer = $(this).next('.shown');
if ($answer.is(':hidden')) {
$answer.show();
$('.hidden').addClass('color1');
} else {
$answer.hide();
$('.hidden').removeClass('color1');
}
});
});
css
.color1{
background:red;
}
jsfiddle
https://jsfiddle.net/Lc5n8k81/1/
Upvotes: 0
Views: 45
Reputation: 136239
Inside your click handler, you want to refer to $(this)
not $('.hidden')
- the latter means all elements with class hidden
:
$('.hidden').click(function () {
var $answer = $(this).next('.shown');
if ($answer.is(':hidden')) {
$answer.show();
$(this).addClass('color1');
} else {
$answer.hide();
$(this).removeClass('color1');
}
});
https://jsfiddle.net/Lc5n8k81/2/
Upvotes: 1
Reputation: 8101
here while adding and removing color1 class change $('.hidden') to $(this).. as $('.hidden') will add class to all element with .hidden class
Jsfiddle: https://jsfiddle.net/6moznpbr/
$(document).ready(function () {
$('.shown').hide();
$('.hidden').click(function () {
var $answer = $(this).next('.shown');
if ($answer.is(':hidden')) {
$answer.show();
$(this).addClass('color1');
} else {
$answer.hide();
$(this).removeClass('color1');
}
});
});
Upvotes: 1