Daniel Brady
Daniel Brady

Reputation: 954

Cannot add click events to list items

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>

Upvotes: 11

Views: 52015

Answers (5)

rasyidcode
rasyidcode

Reputation: 588

You can also do it by using querySelectorAll

  <ul class="stuffList">
    <li>Stuff 1</li>
    <li>Stuff 2</li>
    <li>Stuff 3</li>
    <li>Stuff 4</li>
    <li>Stuff 5</li>
  </ul>
    
<script type="text/javascript">
    document.querySelectorAll('ul.stuffList li').forEach((item) => {
        item.addEventListener('click', (e) => {
            console.log(e.target)
        })
    });
</script>

Upvotes: 0

Shapon Pal
Shapon Pal

Reputation: 1146

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>

Upvotes: 0

cooshal
cooshal

Reputation: 778

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 !

Upvotes: 22

adeneo
adeneo

Reputation: 318302

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

Upvotes: 9

Mehdi Benmoha
Mehdi Benmoha

Reputation: 3935

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()">

Upvotes: -1

Related Questions