Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write one line window events in javascript?

Tags:

javascript

I'm checking for three window events in my script:

window.onload = updateData;
window.onresize = updateData;
window.onscroll = updateData;

How could I optimize my code and write this in one line? I tried:

window.onload || window.onresize || window.onscroll = updateData;

but it doesn't work.

like image 778
easwee Avatar asked Dec 29 '25 03:12

easwee


2 Answers

window.onload = window.onresize = window.onscroll = updateData;

If this was a normal variable assignation such as: a = 1 this would return 1,

so in b = a = 1 , the b var receives the value 1 from the previous assignation and the current on returns 1 too as result.

On the other hand I would suggest that the updateData function would implement some race condition control to prevent that routine to be running simultaneously.

like image 199
Edorka Avatar answered Dec 30 '25 16:12

Edorka


If you have a lot of properties to assign, then

['onload', 'onresize', 'onscroll'].forEach(function(x){window[x] = updateData})

will eventually be shorter.

like image 36
Wolfgang Kuehn Avatar answered Dec 30 '25 15:12

Wolfgang Kuehn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!