Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Listen to only window's width change (not height)

I’m aware of

window.addEventListener('resize', function(event) {}

and

window.onresize = function(event) {}

But is there a way to listen to WIDTH only ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would like the simplest way to trigg an event when ONLY the window’s width is changing.

To give some context, actually I’m using

window.onresize = function(event) {}

and I’m trying to prevent the function to trig when you scroll down in iOs Safari.

Thanks to who can help.

>Solution :

You can achieve this behavior by storing the last width in a variable. and then compare the last width with the current width if they are not equal then do whatever you want and then update the last width.

let lastWidth = window.innerWidth

window.onresize = function(event) {
    if (window.innerWidth !== lastWidth) {
        // your code
        
        // update the last width
        lastWidth = window.innerWidth
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading