Reputation: 35
I have the following list element.
<div id="selections">
<ul>
<li><img class="closeArrow">Company 1
<ul class="collapse">
<li><img class="closeArrow">Branch 1-1
<ul class="collapse">
<li>User 1-1-1</li>
<li>User 1-1-2</li>
<li>User 1-1-3</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
I have added the following event handler If I click on "Branch 1-1" I want the second level to have a red border.
$(document).on('click', '#selections ul > li:has(img)',function(e){
$(this).css("border","red thin solid");
}
Currently the second and the first level is changed to a red border.
It appears as if 'this' applies to all elements in the parent ul and not only the child ul that was clicked on.
The idea is to toggle the display of all child elements. So if a user click on Branch 1-1, the User 1-1-x must toggle display. If the user click on Company 1, then Branch 1-1 and its child elements must toggle display. The option being clicked on must remain visable so the user can clikc on it again.
Any advice?
Upvotes: 0
Views: 213
Reputation: 42044
You need to stop event propagation:
[e.stopPropagation();][1]
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
The best solution is based on classes instead to use inline style.
Therefore, if you need to toggle you may use toggleClass() instead of css(). That means you need to define a class instead of using an inline class string. This will avoid the complexity to convert the attributes like the color red to the equivalent rgb value.
The snippet:
$(document).on('click', '#selections ul > li:has(img)',function(e) {
e.stopPropagation();
$(this).toggleClass('newBorder');
});
.newBorder {
border: red thin solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selections">
<ul>
<li><img class="closeArrow">Company 1
<ul class="collapse">
<li><img class="closeArrow">Branch 1-1
<ul class="collapse">
<li>User 1-1-1</li>
<li>User 1-1-2</li>
<li>User 1-1-3</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
Upvotes: 2