Search code examples
javascripthtmldom-eventsmouseevent

Retrieve the index ul li a list


I have a list which, when clicked, gives me its index. The problem I have is that the first time I click, it does not do the action in its entirety. I have to re-click on it and then everything works perfectly. But I can not find the problem. Can you tell me where I make my mistake?

Here's my list:

<ul id="filesList">
  <li>index 1</li>
  <li>index 2</li>
  <li>index 3</li>
</ul>

Thank you very much for your help!

Here's my code:

filesList.addEventListener('click', function(e) {
for (var i = 0, len = filesList.children.length; i < len; i++) {
    (function(index) {
        filesList.children[i].onclick = function() {
            console.log(files[index]);
            e.stopImmediatePropagation();
        }
    })(i);
  }
});

Solution

  • You are adding the event listener to each li on the click event of the list. That means that you have to click the list once to set the behavior for each item click.

    The solution is very simple, you just have to remove the first and last line:

    for (var i = 0, len = filesList.children.length; i < len; i++) {
        (function(index) {
            filesList.children[i].onclick = function() {
                console.log(files[index]);
                e.stopImmediatePropagation();
            }
        })(i);
    }
    

    Then, when the code loads it will set the click event for each item on the list.

    Update: this javascript should run after the list is created.