0

I'm using the .each method with the .getJSON method to print out objects in a JSON file. This works fine, however I am unable to add a click function to an element that has been printed out. I am trying to bind a function to the div with 'click' ID.

var loadData = function () {
    $.getJSON("profiles2.json", function (data) {
        var html = [];
        html.push("<div id='click'>Click here</div>");
        $.each(data.profiles, function (firstIndex, firstLevel) {
            html.push("<h2>" + firstLevel.profileGroup + "</h2>");
        });
        $("#data").html(html.join(''));
    });
};
$(document).ready(function () {
    loadData();
    $("#click").click(function () {
        console.log('clicked');
    });
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

2 Answers2

2

$.getJSON() (like other Ajax methods) is asynchronous, so it returns immediately before the results have come back. So your loadData() method also returns immediately and you then try to bind a handler to an element not yet added.

Move the .click(...) binding into the callback of $.getJSON(), after adding the element(s), and it will work.

Alternatively, use a delegated event handler:

$("#data").on("click", "#click", function() {
    console.log('clicked');
});

...which actually binds the handler to the parent element that does exist at the time. When a click occurs it then tests whether it was on an element that matched the selector in the second parameter.

And as an aside, don't bind click handlers to divs unless you don't care about people who are physically unable to (or simply choose not to) use a mouse or other pointing device. Use anchor elements (styled as you see fit) so that they're "click"-accessible via the keyboard and the mouse.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

$.getJSON is an asynchronous call and probably hasn't finished by the time you are trying to bind to the element that it injects into your DOM. Put your binding inside the $.getJSON call after you append the element to the page at the bottom.

MBielski
  • 6,628
  • 3
  • 32
  • 43
  • _"probably hasn't finished"_ - It _definitely_ won't have finished, regardless of how fast the Ajax response comes back. The current code block will definitely finish executing before the `$.getJSON()` callback is called. – nnnnnn May 09 '13 at 23:32
  • Thanks for the quick replies guys. I added the .done method to my getJSON and it works. Cheers!!! –  May 10 '13 at 00:04