Using jQuery to select a dynamically created item

Trying to figure this out, and I think I know the problem, but I don't know how to fix it. When my page loads first, I use a JSON file to provide some links on the page, using $ .getJSON to create them and give them identifiers, dynamically. My code for this (this is just what interests me, I, of course, close the function):

$(function() { $.getJSON("data.json", function(data) { var navOutput = ""; for (var key in data.navigation) { navOutput += '<li><a id="' + key + '">' + data.navigation[key] + '</a></li>'; // Create list items with ID 'key' } $("#mainNav").html(navOutput); 

Everything loads fine on the page. Outside of the $ .getJSON function, I am trying to assign an event listener to one of these dynamically created identifiers as an example:

 $("#cast").click(function() { alert("Testing"); }); //click function 

This does not work. There is probably a simple answer to this question, but I cannot figure it out. If I assign an event handler to an identifier on a page created in HTML, it works, so it has something to do with these dynamic identifiers. Any help would be appreciated.

+4
source share
1 answer

Change

 $("#cast").click(function() { alert("Testing"); }); 

to

 $("body").on("click","#cast",function(e) { alert("Testing"); }); 

You need to set the on handler instead of click . This is promotion to live() . This will allow you to bind a handler to dynamically loaded elements. click will only attach to dom ready, i.e. when the page is first layered.

+10
source

All Articles