I am looking to achieve a functionality where, upon clicking on a span with the class ColOpen, it gets replaced with ColClosed and the corresponding ul element is hidden. However, I am unsure about how to identify which specific span was clicked by the user.
One approach to solve this issue is by listening for click events on a container element (such as the treeview) and instructing jQuery to only trigger an action if the click occurred on either a .CollOpen or .CollClosed span (this technique is known as event delegation):
$(".treeView").on("click", ".CollOpen, .CollClosed", function() {
// ...
});
Within the event handler, the context of `this` refers to the exact span that was clicked, allowing us to toggle classes and hide subsequent ul elements:
$(this).toggleClass("CollOpen CollClosed").nextAll('ul').first().toggle();
Putting it all together:
$(".treeView").on("click", ".CollOpen, .CollClosed", function() {
$(this).toggleClass("CollOpen CollClosed").nextAll('ul').first().toggle();
});
To illustrate further:
$(".treeView").on("click", ".CollOpen, .CollClosed", function() {
$(this).toggleClass("CollOpen CollClosed").nextAll('ul').first().toggle();
});
.treeView {
-moz-user-select: none;
position: relative;
}
/* CSS styling continues... */
<ul class="treeView">
<li>
<span class="CollOpen">[*]</span><span>Collapsible lists</span>
<ul class="CollList">
<li>
<span class="CollClosed">[*]</span><span>Actions</span>
<ul class=" CollList" style="display: none;">
<li class="lastChild">
<span class="CollOpen">[*]</span><span>Actions</span>
<ul class="CollList" style="display: none;">
<li class="">Expanding/opening</li>
<li class="lastChild">Collapsing/closing</li>
</ul>
</li>
</ul>
</li>
<li class="lastChild">
<span class=" CollOpen">[*]</span><span>Actions</span>
<ul class="CollList" style="display: none;">
<li class="">Directory listings</li>
<li class="">Tree views</li>
<li class="lastChild">Outline views</li>
</ul>
</li>
</ul>
</li>
</ul>
It's worth noting that I've added [*] to the spans for better visibility and interaction. Alternatively, instead of toggling between .CollOpen and .CollClosed, consider rendering the elements consistently with a class on the li element to handle the open/close state. This can lead to more streamlined code management while maintaining a cohesive design across the spans within li elements.