Search code examples
javascriptwindowresizewidth

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 ?

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
        }
    }