Sorry if my question is really for newbie level…
I have a 3 level list to build a menu, but I don’t want to use href.
I would like to use a specific attribute instead and call a javascript function with it value.
Here is the markup of my example-list:
<ul class="menu">
<li><a href="#" link_value="item 1">Firts level Menu item 1</a></li>
<ul>
<li><a href="#" link_value="item 2-1">Second level Menu item 1</a></li>
<ul>
<li><a href="#" link_value="item 3-2-1">Third level Menu item 1</a></li>
<li><a href="#" link_value="item 3-2-2">Third level Menu item 2</a></li>
<li><a href="#" link_value="item 3-2-3">Third level Menu item 3</a></li>
</ul>
<li><a href="#" link_value="item 2-2">Second level Menu item 2</a></li>
<li><a href="#" link_value="item 2-3">Second level Menu item 3</a></li>
</ul>
<li><a href="#" link_value="item 2">Firts level Menu item 2</a></li>
<li><a href="#" link_value="item 3">Firts level Menu item 3</a></li>
How could I run a javascript function to set onclick event for all a items to have something like
<a onclick="my_fynction()">
function my_fonction() {do_something(link_value)}
and also add an ‘active’ class to the active element and his parent levels and remove the active class from the others ?
Hope I have been clear enough ?
Many thanks !!!
2
Answers
You can listen to clicks on
ul.menu
and put your event logic only on this element.But you’d need to be careful if you put
<span>
for example inside<a>
. You’d need to put CSSpointer-events: none;
on these elements.Regarding both of my above comments …
… and after having fixed the markup, one should make use of, as already suggested but not explicitly named, event-delegation.
The latter does not only mean listening at a common (outer) root node, it also means targeting the element/s of interest which, like the root-node, might have child element-nodes as well.
Thus one always has to query the element/s one is interested in. One mostly does achieve the result by utilizing the
closest
method of theevent
‘starget
element.And regarding another of the OP’s requirements …
… the handler function would pass the currently identified link-element to a custom implemented function, thus forwarding such a special task and not taking care of such stuff by itself.
A function which marks the current menu item has to do following …
identifying the menu-item node … done by …
identifying the menu-root node … done by …
choosing the right selector for querying any list-item node which has a link-element (e.g.
'li:has(a[href])'
) and removing the intended class-name (and/or e.g. aria attributes) from each queried element.adding the intended class-name (and/or e.g. aria attributes) to the list-item which has been identified as current.
It is not necessary to mark any list-item involved in another list-item’s current state as current as well. The visual representation of such a state can be easily achieved by utilizing a functional CSS pseudo-class like
:has()