Mahmoud Santos

21 Feb 2022

jQuery Selector is not working .click

jQuery

I don't know why the .on ('click') code is not working with the selector this code is not working whatever I change the selector

 $(function () {
 $('.todolist input').on('keydown', function(e){
 if(e.keyCode == 13){
 $('<li>' + $(this).val() + '<i class="fas fa-times"></i></li>').appendTo($('.todolist ul'))
 $(this).val('');
 }
 })
})

$(function () {
 $('.todolist .fa-times').on('click', 'li i', function() {
 $(this).parent('li').css('text-decoration', 'line-through').delay(200).fadeOut(300, function () {
 $(this).parent('li').remove();
 });

 });
});

This code is working fine without the selector

 $(function () {
 $('.todolist .fa-times').on('click', function() {
 $(this).parent('li').css('text-decoration', 'line-through').delay(200).fadeOut(300, function () {
 $(this).parent('li').remove();
 });

 });
});

I'm making a to-do list and I want after any <li> created with jQuery when I click on the icon (x) remove it

<div class="container">
<div class="todolist">
 <h3>To Do List:</h3>
 <ul>
 <li>Learning JQuery<i class="fas fa-times"></i></li>
 <li>Codeing My 1st Site<i class="fas fa-times"></i></li>
 <li>Learning Angular js<i class="fas fa-times"></i></li>
 <li>Learning SAS<i class="fas fa-times"></i></li>
 <li>More Training<i class="fas fa-times"></i></li>
 </ul>
 <input type="text" placeholder="Add New Task">
</div>

Comments

Eslam Zedan

21 Feb 2022

Best Answer

best answer

Your delegated event handler has both selector and delegation:

$('.todolist .fa-times').on('click', 'li i', function() {

li i is not a sub-node of .fa-times

change to

$('.todolist').on('click', 'li i.fa-times', function() {

© 2024 Copyrights reserved for web-brackets.com