Strange situation:
I am building a menu bar using jQuery
and CSS
.
In my JavaScript file, I have an on-ready
function like so:
$(document).ready(function(e) {
mark_active_menu();
}
and...
function mark_active_menu() {
var elementWidth = $("nav li").width();
alert(elementWidth);
}
For some reason, even BEFORE all the document finish loading, I'm getting the alert message with an incorrect width. Only when I release the message, the rest of the document loads and I'm getting the right width as it should be.
Why my function is being called BEFORE all the document finish loading?
Is there a way to load the function only AFTER a certain element done loading (Example: the nav
element)?
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
ready( handler )Returns: jQuery. Description: Specify a function to execute when the DOM is fully loaded.
The Document Ready Event This is to prevent any jQuery code from running before the document is finished loading (is ready). It is good practice to wait for the document to be fully loaded and ready before working with it.
after page loading? Method 2: Using the ready() method: The ready() method in jQuery is used to execute code whenever the DOM becomes safe to be manipulated. It accepts a handler that can be passed with the function required to be executed. It will now invoke the function after the page has completed loading.
You can use window.load, it will be triggered after all the resource have completed loading.
$(window).load(function(e) {
mark_active_menu();
});
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading, Reference
All the current solutions are just treating symptoms of the main problem. If you want your handler to execute after all your ajax loads, then you may use a promise.
var ajax1 = $.ajax();
var ajax2 = $.ajax();
jQuery(function($) {
$.when.apply($, [ajax1, ajax2]).done(function() {
// your code here
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With