Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How come my 'click' eventListener works for the first 2 <li>'s and not the rest?

I am relatively new to programming. I got my ‘click’ eventListener to work, and when you click on the first two li’s in the ul, the class of the div toggles on and off. However, when you click on any li after the second one, it toggles the class of every other div and not the one that is clicked on? If you need more clarification regarding the situation, feel free to let me know.

For example, if the for loop were to print:

  • Bench Press
  • Deadlift
  • Squat
  • Shoulder press
  • Curl

If i click on ‘bench press’ and ‘deadlift’ it will toggle .info and show the information for it; but if i were to click on ‘squat’ it will toggle .info for the ‘curl’ instead, so on and so forth…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is all the code,

<div>
    {% for workout in workouts %}
    <ul>
        <li class="item">{{ workout.name }}</li>

        {% autoescape false %}
        <div class="info" id="info">
            <p>{{ workout.description }}</p>
        </div>
        {% endautoescape %}
    </ul>
    {% endfor %}
</div>
let li = document.querySelectorAll("li");
let info = document.querySelectorAll(".info");

for (let i = 0; i < li.length; i++) {
  li[i].addEventListener("click", function () {
    info[i].classList.toggle("info");
  });
}
.info {
  display: none;
}

>Solution :

The i variable stores the last value after the loop, since it is in another callback function.

Try this fix:

let li = document.querySelectorAll("li");
for (let i = 0; i < li.length; i++) {
  let liItem = li[i];
  liItem.addEventListener("click", function () {
    liItem.querySelector("div").classList.toggle("info");
  });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading