Skip to content Skip to sidebar Skip to footer

Call Javascript Function By Clicking On Html List Element

I am new to web development so this question may be too obvious to others. I would like to make a menu, when menu item is clicked it needs to call javascript function with one argu

Solution 1:

This will hopefully get you going in the right direction. All I'm doing is binding an "onClick" event listener to all li elements, you might want to change what you bind to in case you use them elsewhere. Then when they are clicked they call the function myScript which get's their ID and alerts it.

JSFiddle Demo

HTML

<ul>
    <li id="1">Link 1</li>
    <li id="2">Link 2</li>
    <li id="3">Link 3</li>
    <li id="4">Link 4</li>
    <li id="5">Link 5</li>
</ul

Javascript

var li = document.getElementsByTagName("li");

for(var i = 0;i<li.length;i++){
    li[i].addEventListener("click", myScript);
}

functionmyScript(e){
    alert(e.target.attributes.id.value);       
}

Post a Comment for "Call Javascript Function By Clicking On Html List Element"