Cannot add click events to list items

addeventlistener
javascript onclick multiple elements
javascript for loop click event
getelementsbyclassname
javascript add click event to array of elements
add event listener to all buttons
onclick event in li tag
onclick javascript

This is my first foray into using Javascript with HTML. I'm trying to add click events to the list items in an ordered list, but something about the way I'm doing it isn't working. Can somebody shed some light on this for me?

I create a function in my head that should delegate all click events on the list items of a specified list to a given function, and in that given function I try to raise a simple alert with the text of the list item. Eventually I want to do more, but I'm just trying to get the simple click events to work first.

<html>
    <head>
    <script type="text/javascript">
      // Attach an event handler to the 'topfriends' list to handle click events.
      function attachEventHandlerToList() {
          document.getElementById("#top4list").delegate("li", "click", function(clickEvent) {
              alert(this.innerHTML());
          });
        }
    </script>
</head>

<body>

    <div id="topfriends">
        <h3>Top 4 Most Friendable Friends</h3>
        <ol id="top4list" onload="attachEventHandlerToList()">
            <li>Brady</li>
            <li>Graham</li>
            <li>Josh</li>
            <li>Sean</li>
        </ol>
    </div>
</body>

Let's do something like this

<ul id="parent-list">
    <li id="a">Item A</li>
    <li id="b">Item B</li>
    <li id="c">Item C</li>
    <li id="d">Item D</li>
    <li id="e">Item E</li>
    <li id="f">Item F</li>
</ul>

Now write the javascript for this

<script type="text/javascript">
    // locate your element and add the Click Event Listener
    document.getElementById("parent-list").addEventListener("click",function(e) {
        // e.target is our targetted element.
                    // try doing console.log(e.target.nodeName), it will result LI
        if(e.target && e.target.nodeName == "LI") {
            console.log(e.target.id + " was clicked");
        }
    });
</script>

Please refer to this write-up on Javascript Event Delegates http://davidwalsh.name/event-delegate

Also, below link is the fiddle that I created http://jsfiddle.net/REtHT/

hope this helps !

How to add a click event to a list of DOM elements returned from , How to iterate a NodeList and attach an event listener to each element. I create a function in my head that should delegate all click events on the list items of a specified list to a given function, and in that given function I try to raise a simple alert with the text of the list item. Eventually I want to do more, but I'm just trying to get the simple click events to work first.

delegate() is a deprecated jQuery method, and no such method exists in plain JS. To attach an event handler in JS you'd use addEventListener, and for older versions of IE you'll need attachEvent as well, that's why it's a little tricky with cross browser event handlers. onclick, onmouseenter etc. will work in all browsers, but it's consider a better practice to use addEventListener / attachEvent.

Also, you have to run the script after the elements are added to the DOM, otherwise they are not available. The usual way is to insert the script after the elements, or use a DOM ready event handler.

<html>
<head>
    <title>test</title>
</head>

<body>

<div id="topfriends">
  <h3>Top 4 Most Friendable Friends</h3>
  <ol id="top4list">
    <li>Brady</li>
    <li>Graham</li>
    <li>Josh</li>
    <li>Sean</li>
  </ol>
</div>

<script type="text/javascript">
    var lis = document.getElementById("top4list").getElementsByTagName('li');

    for (var i=0; i<lis.length; i++) {
        lis[i].addEventListener('click', doStuff, false);
    }

    function doStuff() {
        alert( this.innerHTML );
    }
</script>
</body>

FIDDLE

How to add an event listener to multiple elements in JavaScript, But how can you attach the same event to multiple elements? In other words, how to call addEventListener() on multiple elements at the same  The addEventListener() method attaches an event handler to an element without overwriting existing event handlers. You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.

Try this. It will work with child Node and Parent Node also.

 var visitorList = document.getElementById("visitor");
        visitorList.addEventListener("click", function (e) {
            var visitorId;
            if (e.target && e.target.nodeName == "LI") {
                visitorId = e.target.id;
                console.log(e.target.id);
            }
            if(e.target && e.target.nodeName == "H1") {
                visitorId = e.srcElement.parentElement.id;
                console.log(e.srcElement.parentElement.id);
            }
            //console.log(visitorId);
        });
<ul id="visitor">
        <li id="a" style="background: #CCCCCC; padding: 10px;"><h1 style="background: #437ba9;">Visitor A</h1></li>
        <li id="b"><h1>Visitor B</h1></li>
        <li id="c"><h1>Visitor C</h1></li>
        <li id="d"><h1>Visitor D</h1></li>
        <li id="e"><h1>Visitor E</h1></li>
        <li id="f"><h1>Visitor F</h1></li>
    </ul>

Handling Events :: Eloquent JavaScript, Event listeners are called only when the event happens in the context of the The addEventListener method allows you to add any number of handlers so that list of buttons, it may be more convenient to register a single click handler on Most nodes cannot have focus unless you give them a tabindex attribute, but things  And can anytime adviseHow many items are allowed on watch list? I can't find the info on ebay. It says my list is fill. I've removed dozens of items, but still can't add to watch list.

Hello why not doing it easier by replacing onLoad directy by onClick

<script type="text/javascript">
function olClicked(){
alert(this.innerHTML());
}
</script>
<ol id="top4list" onClick="olClicked()">

Introduction to browser events, Here's a list of the most useful DOM events, just to take a look at: Mouse As there's only one onclick property, we can't assign more than one event handler. The syntax to add a handler: element . addEventListener ( event  Exit_Command8_Click: Exit Sub. Err_Command8_Click: MsgBox Err.Description Resume Exit_Command8_Click. End Sub. Here is the main form again ready to continue data entry after handling the not in list event. Below is the visual basic code used to immediately add the new list item to the lookup table:

.click(), is released while the pointer is inside the element. You already have the click event that you would get with a button. All you really need to do is to make the ListViewItem *look* like a button. You could set your ListView to be an owner drawn listview (OwnerDraw=true) and then wireup paint events to the DrawItem and DrawSubItem events.

JavaScript DOM EventListener, How do I add an event listener to my class? Add onClick event dynamically using javascript : function that will attach the onClick event. Add the following in the script tag of your html page. Each line in the function is self explanatory with comments. We call the function using the window.load event to make sure that the element is loaded before we try to attach the event listener

jQuery Event Methods, The addEventListener() method attaches an event handler to an element You can add event listeners to any DOM object not only HTML elements. For a list of all HTML DOM events, look at our complete HTML DOM Event Object Reference. reviewed to avoid errors, but we cannot warrant full correctness of all content. The only way I can add an event is to go to the menu, select Events and Task and add a new event. Starting Monday, 7/10 I can no longer click on a date in the calendar to add an event. Also, I cannot open and edit any existing events in the calendar.

Comments
  • Ahh, this works too! And I bet it's more efficient than assigning individual click events to each list item, which is what I was trying to avoid by using 'delegate()'.
  • But wait! How can I get at the text within the list item? Using e.target.id gets the id of the li, right? I will be generating this list eventually, and e.target.innerHTML doesn't print out anything.
  • Nevermind, innerHTML totally works. I guess I either misspelled it or didn't save the changes lol. My bad!
  • It's only more efficient when you bind the event handler, after that it's less efficient on every click to check the target everytime someone clicks the parent OL.
  • Thanks for the advice! I'll give this a try. This is really my first time adding behavior to my HTML, so I don't know anything too detailed about event handling. Also, the project I was testing this for uses JQuery, so I thought the delegate() method would be fine, but I guess I need to require the library or something when I use it? I'm new to JS as well.
  • i get a type error when I try this. 'this' is apparently the window, not the list item. The reason I was using delegate is because I need to specify different behavior for each list item.