You need to invoke javascript code:

  1. after loading page
  2. when resizing browser window

This code works for the first case and for some reason does not work for the second:

$(function() { $(window).resize(doSomethingUseful()); }); function doSomethingUseful() { $('body').append('<div>Handler for .resize() called. ' + document.body.clientWidth + '</div>'); } 

But this one works for the second case, but does not work for the first:

 $(function() { $(window).resize(function() { $('body').append('<div>Handler for .resize() called. ' + document.body.clientWidth + '</div>'); }); }); 

See the two test examples below - you can copy them, save and run.

What code will work for both cases?

Updated from comments.

Test Example 1:

 <html> <head> <title>resize</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { $(window).resize(doSomethingUseful()); }); function doSomethingUseful() { $('body').append('<div>Handler for .resize() called. ' + document.body.clientWidth + '</div>'); } </script> </head> <body> <div>hello world :)</div> <hr> </body> </html> 

Test Example 2:

 <html> <head> <title>resize</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { $(window).resize(function() { $('body').append('<div>Handler for .resize() called. ' + document.body.clientWidth + '</div>'); }); }); </script> </head> <body> <div>hello world :)</div> <hr> </body> </html> 

    2 answers 2

    In the first example, you do not specify a function for the size event handler, but call it. Replace $(window).resize(doSomethingUseful()); on $(window).resize(doSomethingUseful); in the first example, and it will work.

    • one
      aha and still need to add doSomethingUseful () after loading the page, like this: <html> <head> <title> resize </ title> <script type = "text / javascript" src = " ajax.googleapis.com/ajax/ libs / jquery / 1.6.2 / ... > <script type = "text / javascript"> $ (function () {doSomethingUseful (); $ (window) .resize (doSomethingUseful);}); function doSomethingUseful () {$ ( 'body'). append ('<div> Handler for .resize () called.' + document.body.clientWidth + '</ div>');} </ script> </ head> <body> <div> hello world:) </ div> <hr> </ body> </ html> and everything works F) Thank you :) - xhr
    • 2
      If I answered your question, then click on the gray tick in the circle to mark this answer as correct. It is located under the "finger down" near the beginning of the answer. - GLAGOLA

    Why use jQuery in such cases?

     window.onresize = func; // при изменении размеров браузера window.onload = func; // при загрузке страницы. 

    I understand, jQuery is multifunctional and convenient, but there are cases when it is redundant, and the creation of the programmer’s hands from its use is a huge crutch .