-3

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.

3
  • 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 li Commented Jul 10, 2014 at 0:23
  • Something like document.getElementsByTagName("li").addEventListener("click", myScript); Commented Jul 10, 2014 at 0:24
  • 3
    @M.chaury , he said he is new to web dev. Commented Jul 10, 2014 at 0:25

1 Answer 1

10

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);
}

function myScript(e){
    alert(e.target.attributes.id.value);       
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.