Jeff Butler Jeff Butler - 3 years ago 84
Javascript Question

$(document).ready(function() vs .click(function()

I have a page that is populated with a $.getJSON() function which is working perfectly, the JSON is being written into the DOM correctly but I have another function that toggles the display of elements on a page if there is a matching value in the query string.

$(document).ready(function () {
$("#one").toggle(data.indexOf("one") !== -1);
$("#two").toggle(data.indexOf("two") !== -1);
$("#three").toggle(data.indexOf("three") !== -1);
$("#four").toggle(data.indexOf("four") !== -1);
});


If I use any other event to fire the function the correct elements are hidden/displayed on the page for example.

$(document).click(function () {
$("#one").toggle(data.indexOf("one") !== -1);
$("#two").toggle(data.indexOf("two") !== -1);
$("#three").toggle(data.indexOf("three") !== -1);
$("#four").toggle(data.indexOf("four") !== -1);
});


Can someone please explain why the .ready() function is not working?

Interestingly loading the content of the page with a $.getJSON() function seems to have something to do with it because if I hard code the HTML then my .ready() function works.

Cheers Jeff

Answer Source

The ready event is fired when your dom page is loaded.

Your getJSON() function is triggered after the dom is loaded !

Add a promise to your getJSON code to change it.

.getJSON().then(function() {
   $("#one").toggle(data.indexOf("one") !== -1);
   $("#two").toggle(data.indexOf("two") !== -1);
   $("#three").toggle(data.indexOf("three") !== -1);
   $("#four").toggle(data.indexOf("four") !== -1);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download