Reputation: 2084
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();
}
});
Upvotes: 3
Views: 7390
Reputation: 1901
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...
Upvotes: 5