Leo
Leo

Reputation: 29

Modify dynamically generated li elements with jQuery when dblclicked

I have a simple To Do list that when a new ToDo is generated it creates and appends a new li element into a preexisting ul. I have a toggleAll()function that adds a class which strikes through the li elements when double clicked. What I want to do now is to create a method that makes it so when I double click an li element, it toggles the line-through class just for the element clicked, so I can mark individual ToDos as completed. I tried using regular JS and jQuery but couldn't find the way to do it with either.

My ToDos are composed of a text property and a boolean determining whether the task is completed or not. Toggling sets the boolean to true, and if the boolean is true, then the .marked class is added to the content of the li element.

addTodo: function(todo){
                this.list.push({
                    todoText: todo,
                    completed: false,
                });
                console.log(this.list);
            },


var view = {
            display: function(){
                var printed = document.getElementById('printedList');
                printed.innerHTML = '';
                for(var i = 0; i < todos.list.length; i++){
                    var newLi = document.createElement('li');
                    newLi.innerHTML = todos.list[i].todoText;
                    printed.appendChild(newLi);
                }
            }
        }
 .marked{
            text-decoration: line-through;
        }
<div id='listica'>
    <ul id='printedList'></ul>
</div>

Edit: toggleAll function:

toggleAll: function(){
                var printedElements = document.getElementById('printedList');
                for(var i = 0; i < todos.list.length; i++){
                    if(todos.list[i].completed == false){
                        todos.list[i].completed = true;
                        printedElements.style.textDecoration = 'line-through';
                    } else if(todos.list[i].completed == true){
                        todos.list[i].completed = false;
                        printedElements.style.textDecoration = '';
                    }
                };

Upvotes: 0

Views: 42

Answers (1)

SimplyComplexable
SimplyComplexable

Reputation: 1114

You can use .addEventListener() or jQuery's .on().

With .addEventListener you need to loop through all of the lis:

const lis = document.querySelectorAll('li');
lis.foreach(function(li) {
    li.addEventListener('dblclick', function(e) {
        e.target.classList.add('line-through');
    });
});

For .on() you don't have to loop through the elements.

$('li').on('dblclick', function(e) {
    $(e.target).addClass('line-through');
});

.on() .addEventListener() event.target NodeList.forEach Element.classList

Upvotes: 1

Related Questions