3

I've seen other questions that were supposed to answer mine, however for some reason, they did not. I am referring to these:
- jquery click event not firing?
- jquery functions dont work on dom elements loaded asynchromously

I first used click() to try to change the color of selected "li" to pink. It worked, but not for the "li"s appended dynamically. I tried to use on() since live() is now deprecated. I was surprised that it still did not work.

This is a sample that you can run:

Javascript:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("ol").append("<li class='test'> Appended item </li>");
  });
});
</script>

<script>
$(function () {
  $('.test').on('click', function () {
    $(this).css("background-color","pink");
  });
});
</script>

HTML:

<body>
  <p>This is a paragraph.</p>
  <p>This is another paragraph.</p>
  <ol>
    <li class='test'> List item 1 </li>
    <li class='test'> List item 2 </li>
    <li class='test'> List item 3 </li>
  </ol>

  <button id="btn1">Append list item</button>
</body>

Does anyone have a clue?
Thanks a lot!

Community
  • 1
  • 1
Khorkhe
  • 1,024
  • 1
  • 11
  • 26

1 Answers1

13

You need to use event delegation based on .on()

$('ol').on('click', '.test', function(el){
    $(this).css("background-color","pink");
})

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531