Cheng Zhaa
Cheng Zhaa

Reputation: 61

How to make script rerun on window resize?

I think the question is pretty much self explanatory...

I've got a script that is drawing some graphics across the window. Currently, if I resize the window (like taking it full screen) the script continues to affect only the windows' initial size. It should rerun, responding to the new dimensions.

I've tried adding this to my script.

$(window).resize(function() {

});

It did run whenever I resized it... but ONLY when I resized it! No more on load... as it also should.

I think I'm on the right path, but what am I missing?

Codepen here.

Upvotes: 0

Views: 3348

Answers (4)

Alain Reve
Alain Reve

Reputation: 321

In the tag :

<body onresize="drawStuff()">

IMHO, it's the easiest way.

Upvotes: 0

Derozer
Derozer

Reputation: 69

All is ok, but when I maximize or restore window, resize event is fired 2 times. When I press F11 in Firefox to go fullscreen, browser's toolbar is sliding up slowly and resize event is fired up to 40 times. My proposal is to use delay:

var timeout;

$(window).resize(function() {
clearTimeout(timeout);
timeout = setTimeout(onResizeOnly, 500);
});

function onResizeOnly()
{
//your code here
}

Upvotes: 0

kidwon
kidwon

Reputation: 4524

function drawStuff() {
   // move here the drawing code ............
};
// call it where the loading process is
drawStuff();

// call it on resize , too
$(window).resize(function() {
   drawStuff();
});

To call on loading

If you are using jQuery:

$(function(){
   drawStuff();
})

if not, try this.

window.onload = function(){
   drawStuff();
}

Upvotes: 1

Kristiyan
Kristiyan

Reputation: 1663

drawingFunction function(){
 // your drawling code;
}

$(window).resize(function() {
 console.log('window is resized');
 drawingFunction();
});

$( document ).ready(function() {
drawingFunction(); // for onload 
});

Upvotes: 1

Related Questions