views:

89

answers:

3

How can I have my javascript code constantly run? The situation is that I want some page elements to be resized when the page resizes. I'm thinking that the way to do this would be to have some javascript code that constantly runs, and whenever the page size changes, it resizes that element.
I tried doing this with setTimeout() and a really small value, but it didn't seem to work.

+5  A: 

http://www.quirksmode.org/dom/events/index.html#t020

You should hook your script to the resize event

Eineki
+1  A: 

I would look at a framework like jquery where you can register a function with a page event.

$('body').resize(function() { ... });

By running the javascript all the time, you run the risk of really bogging down a cpu (especially on single core systems) and really slowing down the browser.

David
+6  A: 

JavaScript is an Event based language, that is you add event listeners to things and then a function is called when that event occurs. This saves you from having a loop run continuously to to check the state of an item.

The window supports onResize in JavaScript, so for example:

window.addEventListener("resize", function(event){
  alert("you just resized the window. If you inspect the event variable you will find some usefull details");
}, false);
Marius
yes, or `window.onresize= function() { ... }`, to avoid the addEventListener-to-attachEvent-fallback-for-IE-support issue, if you don't need multiple resize listeners.
bobince