- #1
Jamin2112
- 986
- 12
... the situation where you want a function to be defined after the DOM is ready, but don't want it to execute right when the DOM is ready (as happens if you simply put it in a document.ready(...) function)?
var myFunction = function() {}; // define the symbol in current scope
$(function() {
var someValueFromDOM = ...;
myFunction = function() {
// use someValueFromDOM
};
});
function myFunction() {
var value = $('#my-text-element').text();
// use value
}
Filip Larsen said:It is a bit unclear to me why you would want to define but not invoke a function when the document is ready. Perhaps you can elaborate on what your problem is?
$('#my-element').hover(function(){ alert("Yo hovered over my element!") });
$(document).ready (function() {
$('#my-element').hover(function(){ alert("Yo hovered over my element!") });
});
harborsparrow said:Sorry I can't really help you.
harborsparrow said:I'd probably end up doing something crass with a timer.
Silicon Waffle said:http://javascriptkit.com/dhtmltutors/domready.shtml
Something similar can be achieved.
harborsparrow said:I notice that the fallback strategy in this article is--a timer!
The Document Object Model (DOM) is a representation of the HTML elements on a webpage. Before the DOM is fully loaded, JavaScript cannot access and manipulate these elements. Therefore, it is necessary to wait for the DOM to be ready before running JavaScript to ensure that all elements are accessible.
There are a few different ways to determine when the DOM is ready. One option is to use the DOMContentLoaded
event, which fires when the initial HTML document has been completely loaded and parsed. Another option is to use the window.onload
event, which fires when all assets on the page, including images and stylesheets, have finished loading.
DOMContentLoaded
and window.onload
?The main difference is that DOMContentLoaded
fires when the HTML document has been loaded and parsed, while window.onload
fires when all assets on the page have finished loading. This means that DOMContentLoaded
may fire earlier than window.onload
, but it does not wait for images and stylesheets to finish loading.
In jQuery, you can use the .ready()
method to execute a function when the DOM is ready. This method is equivalent to using the DOMContentLoaded
event. For example: $(document).ready(function() { // code to run after DOM is ready });
Technically, it is possible to run JavaScript before the DOM is ready by placing the script tag in the head
of the HTML document. However, this is not recommended as it can cause issues with accessing and manipulating HTML elements. It is best practice to wait for the DOM to be ready before running any JavaScript code.