Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript resize event faulty

I don't know why this doesn't work:

window.addEventListener('load', setSize(), false);
window.addEventListener('resize', setSize(), false);

function setSize(){
    width = window.innerWidth;
    console.log(width);
}

It logs the width right after load, but it doesn't do that when I resize.

like image 922
MinestoPix Avatar asked Apr 17 '14 00:04

MinestoPix


1 Answers

Instead of executing the function (and passing the result) :

window.addEventListener('load', setSize(), false);
window.addEventListener('resize', setSize(), false);

you should pass a reference to the function:

window.addEventListener('load', setSize, false);
window.addEventListener('resize', setSize, false);

The function will execute when the event listener triggers.

like image 73
sanchez Avatar answered Oct 18 '22 19:10

sanchez