-2

lib-used:- http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js

jquery

$(document).ready(function(){
       $("#dynamic").append("<div class=id1>Dynamically created click</div>");
       $("#id1").click(function(){
        alert("triggerd func is:"+(this));
     });
});

html

<body>
    <div id="id1">Hard Coded Click</div><!-- working -->
    </br>
    <div id="dynamic"></div><!-- not working -->
</body>
bipen
  • 36,319
  • 9
  • 49
  • 62

4 Answers4

2

the reaosn yours is not working is ..your click event selects all element with id as id1 so the dynamically added elements has class instead of id.. so the event doesnot work...

one way of doing it is to

your selector should be class selector...not id...use on delegated event for dynamically added elements for that event to work.

 $("#dynamic").on('click','.id1',function(){
                alert("triggerd func is:"+(this));


  });

NOTE: id should always be unique and for the hardcoded div to work you should chnage the id to class

  <div class="id1">Hard Coded Click</div><!-- working -->
   //--^^^^^----here
bipen
  • 36,319
  • 9
  • 49
  • 62
1

These answers do include the right code (using on) but they don't explain the fact that in order for your click listener to fire, using the click() method, the element has to be loaded in before you bind the events.

Therefore this will work:

$("#dynamic").append("<div class='id1'>Dynamically created click</div>");
$(".id1").click(function(){
    alert("triggerd func is:"+(this));
});

But this wont

$(".id1").click(function(){
    alert("triggerd func is:"+(this));
});
$("#dynamic").append("<div class='id1'>Dynamically created click</div>");

So basically if you use .on('click', '.id1', ....) It will fire either way.

Also for the sake of having everything in the same answer, your selector is based on an ID attribute rather than the class name you're using.

Ignas
  • 1,965
  • 2
  • 17
  • 44
0

You are binding click event to element with Id = id1. It won't be triggered if you click element with different Id.

Add class to both divs and adjust your click event selector to that class, ie.

$("body").on("click", ".divsClass", function(){
            alert("triggerd func is:"+(this));
});
kul_mi
  • 1,131
  • 5
  • 15
  • 33
0

use on instead of click.Code will be something like this

$(document).on('click','.id1',function(){
        alert("triggerd func is:"+(this));
});

I hope it will help

Sonu Sindhu
  • 1,752
  • 15
  • 25