Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to select a dynamically created element

Trying to figure this one out and I think I know the problem but I don't know how to fix it. When my page first loads I'm using a JSON file to provide some links on the page, using $.getJSON to create them and give them ID's, dynamically. My code for that is (this is just the bit I'm interested in for now, 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 those dynamically created ID's, as an example:

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

This doesn't seem to work. There is probably a simple answer to this but I can't figure it out. If I assign an event handler to an ID on the page created in the HTML, it works, so it has something to do with these dynamic ID's. Any help would be appreciated.

like image 898
Thomas Avatar asked Dec 26 '22 06:12

Thomas


1 Answers

Change

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

to

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

You need to set handler with on instead of click. It's advancement to live(). It'll allow you to attach handler to dynamically loaded elements. click will attach only on dom ready ie while page is laoded initially.

like image 128
SachinGutte Avatar answered Jan 05 '23 15:01

SachinGutte