0

I have problem when I try append li element to list using jQuery. When I create static li element in HTML mouseenter and mouseleave function work ok. But when I want to add li element using append function mouseenter does not work. Can you explain me, where I make the mistake?

$(document).ready(function() {
  var input = $('.task-input');
  var span = '<span class="remove"><i class="fa fa-trash" aria-hidden="true"></i></span>'

  $('.add-button').click(function() {
    if(input.val() == '') {
      var margin = 10;
      for(var i = 0; i < 10 ; i++) {
        $(this).animate( {
            'margin-left': '+=' + (margin = -margin) + 'px'
         }, 50);
      }



    }
    else {
      $('ul').append('<li><p class="task">'+input.val()+'</p>'+ span +'</li>');
      input.val('');
    }

  })

  $('.list').find('li').mouseenter(function() {
    $(this).css({
      'background-color':'yellow'
    })
    $('.remove').css({
      'display':'block'
    })

    $('.remove').click(function() {
      $(this).parent().remove();
    })
  })

  $('.list').find('li').mouseleave(function() {
    $(this).css({
      'background-color':'lightgray'
    })

    $('.remove').css({
      'display':'none'
    })
  })



})

https://jsfiddle.net/nvmgtwq0/2/

mati
  • 87
  • 1
  • 3
  • 9
  • I was going to recommend you use the on() method but I believe Rory is 100% correct that the link he provided already answers your question and this is a duplicate. http://api.jquery.com/on/ – Master Yoda Aug 21 '17 at 14:15
  • You have to reapply the functions used to handle the mouse events immediately after the new list item is added. – William Callahan Aug 21 '17 at 14:16

0 Answers0