Newbie question: how to trigger the execution of the following adaptive layout script when the page width is changed, if the script is in an external file (the link to it is added to <head> and it is executed once the page is formed)?

 $(document).ready(function(){ var vp_width = $(window).width(); if (vp_width >= 240 && vp_width <= 320){ ... } }); 

I already learned that you should add an attribute with the value of <body> with the value of onResize , it remains only to deal with the value of this attribute. If this function had a name, it would not be difficult to call, but then there is just a construction with a function without a name.

  • see the answer in this question: ru.stackoverflow.com/questions/529120 - MasterAlex
  • Thank you, I think this is what we need. But is it possible to avoid repeating the code in two functions? - Bokov Gleb
  • make a function with the necessary code function runCode() { // код } and add a call to this function wherever you need runCode(); - MasterAlex

1 answer 1

Using the bind method:

 function body_resize() { var vp_width = $(window).width(); if (vp_width >= 240 && vp_width <= 320){ alert("body has width >= 240 and <= 320"); } } $(document).ready(function(){ body_resize(); }); $(window).bind("resize", function() { body_resize(); alert("body has resize"); }); 
 body { border: 1px solid red; } 
 <!DOCTYPE html> <html> <head> <script src="//code.jquery.com/jquery.min.js"></script> </head> <body> test </body> </html> 

PS This example cannot be tested on this site, try here.