sami54 sami54 - 1 month ago 10
Javascript Question

reload an javascript animation when resize the window

I did a javascript animation in 3D with three.js and I want reload the page or the animation when I resize the window, so tried that:



window.addEventListener('resize', function(event){
window.location.reload(true);
});





but it's didn't work... I need help

( I am a beginner in javascript)

Answer

Since you are trying to call this function on the resize of the window, you will want to bind the function to the window and not to the document. To support versions of IE that are less than 9, you will want to use attachEvent. Please note that attachEvent requires you to specify the on keyword. Here is an example:

P.s.: If you want to exact answer you should give more information about your browser and version.

if(window.attachEvent) {
    window.attachEvent('onresize', function() {
        alert('attachEvent - resize');
    });
}
else if(window.addEventListener) {
    window.addEventListener('resize', function() {
        console.log('addEventListener - resize');
    }, true);
}
else {
    //The browser does not support Javascript event binding
}

Similarly, you can remove events in the same way

if(window.detachEvent) {
    window.detachEvent('onresize', theFunction);
}
else if(window.removeEventListener) {
    window.removeEventListener('resize', theFunction);
}
else {
    //The browser does not support Javascript event binding
}

Source

Page reloading doesn't same for all browser. Because of that you should look these page reloading examples also. Javascript 1.0

window.location.href = window.location.pathname + window.location.search + window.location.hash;
// creates a history entry

Javascript 1.1

window.location.replace(window.location.pathname + window.location.search + window.location.hash);
// does not create a history entry

Javascript 1.2

window.location.reload(false); 
// If we needed to pull the document from
//  the web-server again (such as where the document contents
//  change dynamically) we would pass the argument as 'true'.

Source