Difference between $ (window) and $ (document)

5

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

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

And this initialization:

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

Would it work if it were like this?

$(document).on('ready load resize', function(){
    
asked by anonymous 24.04.2015 / 21:57

1 answer

9

$ (window)

The $(window) object refers to the window, viewport of the browser that is running the site. With it it is possible to capture the dimensions of the window, how much the user used the scroll, etc. With this object, you can execute code when the entire page is loaded, including images, scripts, styles, and the like. That is, the code will only run when everything is complete. 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 $(document) object references the document as a whole. This document I refer to is the DOM, all elements of the page (HTML code). This is the most used because the script will immediately after the elements load, regardless of the 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:

24.04.2015 / 22:17