Search code examples
javascriptjquerytoggleclass

ToggleClass() on user generated element doesn't work


I am developing a to-do list. I want to toggle the class of a HTML list-element, that represents a to-do. The list-element is generated by the user after the page has been loaded. The ToggleClass-function I have now doesn't work. I am able to catch the dblclick event in the console, but the class does not toggle.

The JavaScript/Jquery looks like this:

$(document).ready(function () {
    $(document).on("dblclick", ["li"], setStatus); 
    console.log("Call setStatus");
});

And the setStatus function:

setStatus = function (){ 
    console.log("Double clicked on the li");
    $(this).toggleClass("done");
}; 

The HTML

 <body>
        <div id ="todoList">
            <ul></ul>
        </div>
        <input type ="text" id ="todoText"/>
        <button id ="addTodoButton">Add!</button>
    </body>

The CSS-class

.done{
    color: #006600;
}

Solution

  • $(document).ready(function () {
        $(document).on("dblclick", "li", setStatus); 
        console.log("Call setStatus");
    });
    

    Remove [] from ["li"], it is not a valid selector, your code fired the callback so showed the message in console.