Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript window resize function that triggers only on width or height change, not both?

I would like to write a Javascript function that triggers only when the window width is resized, not when the window height is resized (or vice versa).

I know that the $(window).on('resize') function exists in jQuery. But it triggers when either the window width or height is resized; to my knowledge, it's unable to isolate changes in one dimension or the other.

I've come up with a hack-y solution that stores the previous window width as a variable, then constantly updates it when the resize function is called and compares the new value against the old. However, this solution seems unnecessarily memory-intensive for such a simple operation.

Is there an easier / less memory-intensive way to detect changes in a single window dimension?

    // Create a variable to store the width of the window
    var windowWidth = $(window).width();

    // When the window is resized...
    $(window).on('resize', function(){

        // If the window width has changed...
        if(windowWidth != $(window).width()) {

            // Store new window width in the variable and run my function
            windowWidth = $(window).width();

            executeMyDesiredCode();
        }
    });
like image 503
Sam Avatar asked May 03 '26 19:05

Sam


1 Answers

Just need to use a prevWidth or prevHeight variable:

With ResizeObserver:

var prevWidth = window.width;
var observer = new ResizeObserver(function(entries) {
    const width = entries[0].borderBoxSize?.[0].inlineSize;
    if (typeof width === 'number' && width !== prevWidth ) {
        prevWidth = width;
        console.log(width);
    }
})
observer.observe(window.document.body);

With onResize event:

var prevWidth = window.innerWidth;
window.addEventListener('resize', function() {
    var width = window.innerWidth;
    if (width !== prevWidth) {
        prevWidth = width;
        console.log(width);
    }
});

PS: just noticed you already know about this solution, but still decided to leave it here for future readers...

like image 114
Inc33 Avatar answered May 06 '26 10:05

Inc33



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!