I have the following code:
function drawDimensions(divid) {
// This function gets a JSON file, loops through the JSON code using $.each and fills the divid with parsed JSON content
}
On the other hand, I have 2 functions that allows me to toggle the menu and submenus by using $.toggle().
What should I be loading under $(document).ready(function() { });?
At the moment, I’m loading the drawDimensions and the toggle functions under it, but the toggle does not work. Do I need to load them in a certain order within the document ready function? Does it matter?
Note: toggle functions work if I disable the drawDimensions and simply attach the output html to the code.
You put your code inside a
$(document).ready()closure to make sure that the DOM is fully parsed before running any JavaScript on it.It sounds like you are dynamically adding HTML to the DOM, in which case you have to “do work” on that HTML after it is added or use event delegation to bind your event to elements which are added to the DOM later:
Here is a demo: http://jsfiddle.net/76uTr/2/ (note: use the “add menu” link to dynamically add another menu to see that the event bindings work for elements added dynamically to the DOM)
Instead of binding event handlers directly to elements, this will allow you to setup event handlers for elements that will be added to the DOM in the future.
Note that
.on()is new in jQuery 1.7 and in this case is the same as.delegate()(the syntax is a bit different but you can see that in the docs)..on(): http://api.jquery.com/on.delegate(): http://api.jquery.com/delegateI grabbed this code from my answer to your question earlier today: jQuery toggle children of div