Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140788

How do I add event listeners to dynamically created HTML list elements?

$
0
0

I'm attempting to make a to-do list application where when a clicked, a list element toggles to a class checked that adds a strikethrough style. I'm having trouble targeting one list element at a time and not checking off the whole list. How can I dynamically add event listeners for each item? Currently, with the below code, items added are already checked and I cannot figure out why.

My HTML appears as follows:

<div id="body">
            <form id="form" onsubmit="newElement()" target="_self">
                <input type="text" id="task" placeholder="What's on the agenda?">
            </form>

            <ul id="list">
                <li class = "checked">test</li >
            </ul>
        </div>

My function grabs data from a text box through this function

function newElement() {
    event.preventDefault(); // stop default redirect

    /* create a list item and put the inputted text within */
    var li = document.createElement("li"); // create a list item
    var inputValue = document.getElementById("task").value; // value of text box
    var t = document.createTextNode(inputValue); // create a text node of the box value
    li.appendChild(t); // put the text node in the li
    li.addEventListener('click', checkToggle(li)); // add event listener for a click to toggle
                                                   // a strikethrough

    /* append the li item to the ul */
    appendItem("list", li); 
}

and then the checkToggle function appears as follows

/* make items get checked when clicked */
function checkToggle(li) {
    li.classList.toggle("checked");
}

However, when the page is loaded, every element is automatically checked when added already.


Viewing all articles
Browse latest Browse all 140788

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>