I am using dust.js ( after much googling for a lack of good documentation ). Finally I was able to create a hyperlink dynamically.Now I want to give an onclick functionality to the dynamically generated hyperlink.
function createLink(){
// register the template loading method with dust now
var compiled = dust.compile("Hello <a href='#' id='linked'>{name}</a>!", "intro");
dust.loadSource(compiled);
dust.render("intro", {name: "Fred"}, function(err, out) {
console.log(out);
$("#displayHelloSection").html(out);
});
}
Below is my document ready. Strangely , when I click on the hyperlink generated , I get Apple , but not Orange. I am curious to know why the second onclick did not work ? The difference is ,In the first one , I am using document to refer to my id ('#linked').In the second one I am directly accessing the id.
$(document).ready(function() {
$(document).on('click','#linked',function(e){
alert("Apple");
});
$('#linked').on('click', function() {
alert('Orange');
});
});
Event handlers specified like this:
$('#linked').on('click', function() {
try to attach themselves to the "#linked"
object at the time this code is run. If the object is not present at the time this line of code runs, then no event handler is created.
Event handlers like this:
$(document).on('click','#linked',function(e){
are delegated event handlers. The event handler is attached to the document
element which always exists so it can be attached at any time. It then relies on event propagation for events that actually originate on other elements to bubble up to the document
element and when the event handler sees the event, it looks to see what element it originated on to see if that matches "#linked"
. This allows the "#linked"
content to come and go or be created later without affecting the event handler.
So, when dealing with dynamically inserted content that you want event handlers on, you have a couple options:
.on()
to specify the child selector that you want it to dynamically look for.You can read these other posts on this topic for more information on delegated event handling:
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Does jQuery.on() work for elements that are added after the event handler is created?