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 argument, the item id. I would like to present menu items as a unnumbered list. What I do not understand is how to bind the same function to each list item, which will be generated by server-side php script.
-
if you are web developer then you should know that you can add lines in echo or print code onclick function or use jquery for click function on ul liM.chaudhry– M.chaudhry2014-07-10 00:23:36 +00:00Commented Jul 10, 2014 at 0:23
-
Something like document.getElementsByTagName("li").addEventListener("click", myScript);sharf– sharf2014-07-10 00:24:05 +00:00Commented Jul 10, 2014 at 0:24
-
3@M.chaury , he said he is new to web dev.bumbumpaw– bumbumpaw2014-07-10 00:25:50 +00:00Commented Jul 10, 2014 at 0:25
Add a comment
|
1 Answer
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.
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);
}
function myScript(e){
alert(e.target.attributes.id.value);
}