Difference between $(window) and $(Document)

Asked

Viewed 4,173 times

5

Is there any difference between using the $(window) e $(document)?

Because from what I found they do the same thing....

And that initialization:

$(window).on('ready load resize', function(){

It would work if it were so?

$(document).on('ready load resize', function(){

1 answer

10


$(window)

The object $(window) refers to the window, viewport of the browser that is running the site. With it it is possible to capture the window dimensions, how much the user used the scroll, etc. With this object, you can execute code when all the page is loaded, including images, scripts, styles and the like. That is, the code will only be executed when everything is done. Example:

$(window).load(function() {
  alert("Página carregada!"); // Esse alert só irá aparecer quando a página estiver completamente carregada
});

$(Document)

Other than $(window), the object $(document) has reference to document as a whole. This document I am referring to is the DOM, all the elements of the page (HTML code). This is the most used, because the script will run immediately after the elements load, independent of images and styles. Example:

$(document).ready(function() {
  alert("DOM carregado!"); // Esse alert irá aparecer imediatamente após o DOM ser carregado
};

The above code can also be written in these other ways:

$(function() {
  alert("DOM carregado!"); // Esse alert irá aparecer imediatamente após o DOM ser carregado
});

jQuery(document).ready(function() {
  alert("DOM carregado!"); // Esse alert irá aparecer imediatamente após o DOM ser carregado
});

$(document).on('ready', function() {
  alert("DOM carregado!"); // Esse alert irá aparecer imediatamente após o DOM ser carregado
});

References

Very interesting pages for you to read:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.