JavaScript Window Resize Event

JavaScript window resize event

Best practice is to add to the resize event, rather than replace it:

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

An alternative is to make a single handler for the DOM event (but can only have one), eg.

window.onresize = function(event) {
...
};

jQuery may do some work to ensure that the resize event gets fired consistently in all browsers, but I'm not sure if any of the browsers differ, but I'd encourage you to test in Firefox, Safari, and IE.

Jquery window.resize(event) = {} works for inspect element but not when the chrome (or edge) window is resized

The problem is not with the resize event or with browser. It's occurring because you're using window.screen.width, which is relative to the screen, not to the browser window. It doesn't matter if you resize the browser window, the screen width will not change. For example, if your screen has resolution of 1900x1200, screen.width will always be 1900. Hence, you should use window.innerWidth, or just innerWidth to get the viewport width. To know more, see this question.

Your code would be that way:

(window).resize((event) => {

if (innerWidth <= 540) {

$('.className1').addClass('d-none');
$('.classname2').css("width", "100%");
$('.classname3').css("left", "3%");
$('.classname3').css("width", "100%");
$('.classname4').css("width", "90%");

An example of working code (open the snippet in full page and resize it):

  $(window).resize((event) => {
if (innerWidth <= 540) {
document.write('It\'s working.');
}
});
<html>
<body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>

How to wait for the 'end' of 'resize' event and only then perform an action?

I had luck with the following recommendation: http://forum.jquery.com/topic/the-resizeend-event

Here's the code so you don't have to dig through his post's link & source:

var rtime;
var timeout = false;
var delta = 200;
$(window).resize(function() {
rtime = new Date();
if (timeout === false) {
timeout = true;
setTimeout(resizeend, delta);
}
});

function resizeend() {
if (new Date() - rtime < delta) {
setTimeout(resizeend, delta);
} else {
timeout = false;
alert('Done resizing');
}
}

Thanks sime.vidas for the code!

How to trigger the window resize event in JavaScript?

Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.

window.onresize = doALoadOfStuff;

function doALoadOfStuff() {
//do a load of stuff
}

In this example, you can call the doALoadOfStuff function without dispatching an event.

In your modern browsers, you can trigger the event using:

window.dispatchEvent(new Event('resize'));

This doesn't work in Internet Explorer, where you'll have to do the longhand:

var resizeEvent = window.document.createEvent('UIEvents'); 
resizeEvent.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(resizeEvent);

jQuery has the trigger method, which works like this:

$(window).trigger('resize');

And has the caveat:

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

You can also simulate events on a specific element...

function simulateClick(id) {
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});

var elem = document.getElementById(id);

return elem.dispatchEvent(event);
}

Window resize event

You defined windowWidth globally. The variable is set once, namely when the script first runs. However, the value does not change on resize because you don't tell it to. To change that, bring the variable declaration inside your function. That way it will always change when necessary.

function mobileResponsiveCheck(){
var windowWidth = $(window).width();
if(windowWidth >= 768){
box3Responsiveness();
}
}

$(window).resize(function(){
mobileResponsiveCheck();
});
mobileResponsiveCheck();

Javascript before and after events for window resize

There are no events that fire before resize. Only during resize. Most solutions to do something on rezise use setTimeout to check when a certain amount of time passed since the last resize event. So I guess you're out of luck.

Angular window resize event

<div (window:resize)="onResize($event)"
onResize(event) {
event.target.innerWidth;
}

or using the HostListener decorator:

@HostListener('window:resize', ['$event'])
onResize(event) {
event.target.innerWidth;
}

Supported global targets are window, document, and body.

Until https://github.com/angular/angular/issues/13248 is implemented in Angular it is better for performance to subscribe to DOM events imperatively and use RXJS to reduce the amount of events as shown in some of the other answers.

How to remove a window resize Listener in JS

Try this:

const { resize } = getEventListeners(window);

resize.forEach(({ listener }) => {
window.removeEventListener('resize', listener);
});

The above should result in removing all of the resize listeners attached to the window.

The getEventListeners is a utility function that is not a part of the JavaScript spec. I wouldn't use that in code meant for production.

Another idea that looks worth looking into instead of getEventListeners is intercepting the addEventListener function.

const addEventListener = window.addEventListener;

window.addEventListener = (...args) => {
if (args[0] === 'resize') {
console.log('Resize event attached!', args[1]);
}
addEventListener(...args);
}

We could even go a bit further and block all of the resize event handlers from attaching.

const addEventListener = window.addEventListener;

window.addEventListener = (...args) => {
if (args[0] === 'resize') {
console.log('Resize event trying to attach, but it is being blocked');
} else {
addEventListener(...args);
}
}

Maybe the above is somehow useful in your case.



Related Topics



Leave a reply



Submit