This is such a basic question but I am having trouble finding the answer – How do I implement the action taken when a list item in an Html menu is clicked?
I’m using an list in my code as a menu, say:
<ul >
<li id="link1"><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a>
<ul class="level2">
<li><a href="#">Link 2a</a></li>
<li><a href="#">Link 2b</a></li>
<li><a href="#">Link 2c</a></li>
</ul></li>
</ul>
I tried giving the menu an id, id=”myMenu”, and an onclick event, and the js was called, but I couldn’t see a way to identify which item was clicked, just that an line item was clicked in myMenu.
<ul id="myMenu" onclick="gothere(id)">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a>
<ul class="level2">
<li><a href="#">Link 2a</a></li>
<li><a href="#">Link 2b</a></li>
<li><a href="#">Link 2c</a></li>
</ul></li>
</ul>
<script type="text/javascript">
function gothere(id)
{
alert("got here "+id) ;
}
</script>
I tried adding an id on a child element, id=”link1″, and that worked, but the js was called for the child and then for the parent.
<ul id="myMenu" onclick="gothere(id)">
<li id="link1" onclick="gothere(id)"><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a>
<ul class="level2">
<li><a href="#">Link 2a</a></li>
<li><a href="#">Link 2b</a></li>
<li><a href="#">Link 2c</a></li>
</ul></li>
</ul>
I can use this approach to get what I need but is there a better way?
I am looking for something which sends the least amount of html over the wire (the reason I am redoing this menu from it’s former implementation).
You shouldn’t attach the events inline. Attach them with javascript.
Note that I’m using jQuery for simplicity here:
http://jsfiddle.net/2rjgd/
With vanilla javascript the concept is the same, use the
targetproperty of theeventobject to find out where theclickevent originated from.http://jsfiddle.net/2rjgd/1/ shows how this would be implemented with vanilla js. (in non IE browsers)