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 !!!
You can listen to clicks on ul.menu
and put your event logic only on this element.
document.querySelector('ul.menu').addEventListener('click', event => {
// event.target is clicked element
if(event.target.tagName!=="A") return;
// prevent default behaviour; redirecting
event.preventDefault();
// your code...
})
But you'd need to be careful if you put <span>
for example inside <a>
. You'd need to put CSS pointer-events: none;
on these elements.