4

I have a simple click event using the on function:

$('#listnav li').on({
    click: function(event) {
        console.log('hello world')              
    }, 
    mouseover: function(event) {
        // do something
    }

});

This is working for the ul list with id "listnav". But when I am adding new entries to the ul using jQuery's append function, this function is not called on the new added list items. How can I fix this?

Caspert
  • 4,271
  • 15
  • 59
  • 104
  • $('#listnav').on('click', 'li', function(){ ..... }); – Kevin Bui Dec 22 '17 at 11:30
  • Does seem to work https://jsfiddle.net/lharby/upf0pddh/ I don't usually use this syntax for an on function – lharby Dec 22 '17 at 11:30
  • The difference between their code and mine is that I don't use quotes, so I should it looks like in my situation? – Caspert Dec 22 '17 at 11:31
  • @lharby By adding return false to the end of the click function is not working for me. – Caspert Dec 22 '17 at 11:32
  • It would be good if you could make an mvce https://stackoverflow.com/help/mcve maybe there is something else going on in the code? What is your append function? And can you add the html to your question – lharby Dec 22 '17 at 11:35
  • You can use like this https://jsfiddle.net/kLbrngo5/ @Caspert – Muhammet Can TONBUL Dec 22 '17 at 11:36
  • It's working, `dynamicli` is being added and when you click on the new li it is returning (event.target.innerHTML) in the console. – lharby Dec 22 '17 at 11:41
  • @lharby Do you have a link? Previous link is the same as before. – Caspert Dec 22 '17 at 11:42
  • I updated the same fiddle adding a console.log to prove the function was working after dynamic elements had been added. – lharby Dec 22 '17 at 12:07

1 Answers1

5

I have also faced same issue,

While you dynamically append anything (here you are adding new entries to ul), you need to bind its event too. as event is already binded when DOM is loaded and the append is made later on. You need to define the click function within the function of Append after your required append is done.

Hope this helps.

sSD
  • 282
  • 2
  • 17
Divya
  • 1,203
  • 2
  • 13
  • 31