Javascript window resize trigger

Cross-browser window resize event — JavaScript / jQuery

What is the correct (modern) method for tapping into the window resize event that works in Firefox, WebKit, and Internet Explorer? And can you turn both scrollbars on/off?

I’m also looking into this. I’d like to try to apply the solutions offered here, but I’m afraid I don’t understand the syntax: $(window). Is that something specific to jquery?

11 Answers 11

For the sake of UI responsiveness, you might consider using a setTimeout to call your code only after some number of milliseconds, as shown in the following example, inspired by this:

function doSomething() < alert("I'm done resizing for the moment"); >; var resizeTimer; $(window).resize(function() < clearTimeout(resizeTimer); resizeTimer = setTimeout(doSomething, 100); >); 

Elijah, this is JavaScript. What you wrote is not correct (except for one specific case when you are constructing with new).

It’s worth mentioning that this jQuery function «adds» a function call to the current list of functions that should be called on a window resize. It does not overwrite existing events that are currently scheduled on a window resize.

$(window).bind('resize', function () < alert('resize'); >); 

I prefer the bind approach, since the resize() method is actually actually a shortcut for the full bind approach, and I often find that there is usually more than one event handler I should be applying to an element.

Читайте также:  Python ldap install error

@Mike — Not only that, but I’m guessing the resize method has no «unbind» method in the event you want to remove the listener. «bind» is definitely the way to go!

Here is the non-jQuery way of tapping into the resize event:

window.addEventListener('resize', function(event)< // do stuff here >); 

It works on all modern browsers. It does not throttle anything for you. Here is an example of it in action.

this solution wouldn’t be working in IE. Fixed version with support of IE dom: stackoverflow.com/questions/6927637/…

> It does not throttle anything for you. Could you please elaborate? What should/would it throttle? Does it relate to the event firing many times in a row?

@josinalvo generally when you’re listening to an event that fires a lot you’ll want to debounce (e.g. lodash) it so you don’t cause a bottleneck in your program.

Sorry to bring up an old thread, but if someone doesn’t want to use jQuery you can use this:

function foo(); window.onresize=foo; 

Just be aware that this will clobber any existing handlers that may be bound to window.onresize. If your script has to live an an ecosystem with other scripts, you shouldn’t assume your script is the only one to want to do something on window resize. If you can’t use a framework such as jQuery, you should at least consider grabbing the existing window.onresize, and adding your handler to the end of it, rather than completely clobbering it.

@TomAuger «you should at least consider grabbing the existing window.onresize, and adding your handler to the end of it» — you probably meant the opposite, i.e. «to call existing handler at the end of your handler»? I would really like to see a javascript code that would add something to the end of already existing function 🙂

I see your point, in a sense — your new onResize handler needs to wrap the existing onResize. However, it doesn’t have to call the function you wanted to add to onResize until after it has called the original onResize handler. So you can still make sure your new onResize function executes after the original onResize function, which is probably better than the reverse.

Since you are open to jQuery, this plugin seems to do the trick.

Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):

// did not work in IE10 $(function() < $(window).resize(CmsContent.adjustSize); >); 

while this worked in both browsers:

// did work in IE10 $(function() < $(window).bind('resize', function() < CmsContent.adjustSize(); >; >); 

Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.

There’s two changes. Which one had the effect? ( .resize() to .bind(‘resize’) or adding the anonymous function? I’m thinking it’s the second.)

@WraithKenny Good point. It very well may be that adding the anonymous function was what made it work. I don’t recall if I tried it.

In the first case, the adjustSize method loses its context of this , whereas the second call CmsContent.adjustSize() preserves this , i.e. this === CmsContent . If the CmsContent instance is required in the adjustSize method, then the first case will fail. Second case will work for every kind of function call, so it’s recommended to always pass an anonymous function.

jQuery provides $(window).resize() function by default:

  

I consider the jQuery plugin «jQuery resize event» to be the best solution for this as it takes care of throttling the event so that it works the same across all browsers. It’s similar to Andrews answer but better since you can hook the resize event to specific elements/selectors as well as the entire window. It opens up new possibilities to write clean code.

There are performance issues if you add a lot of listeners, but for most usage cases it’s perfect.

I think you should add further control to this:

 var disableRes = false; var refreshWindow = function() < disableRes = false; location.reload(); >var resizeTimer; if (disableRes == false) < jQuery(window).resize(function() < disableRes = true; clearTimeout(resizeTimer); resizeTimer = setTimeout(refreshWindow, 1000); >); > 

hope it will help in jQuery

define a function first, if there is an existing function skip to next step.

browser resize use like these.

Besides the window resize functions mentioned it is important to understand that the resize events fire a lot if used without a deboucing the events.

Paul Irish has an excellent function that debounces the resize calls a great deal. Very recommended to use. Works cross-browser. Tested it in IE8 the other day and all was fine.

Make sure to check out the demo to see the difference.

Here is the function for completeness.

(function($,sr)< // debouncing function from John Hann // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ var debounce = function (func, threshold, execAsap) < var timeout; return function debounced () < var obj = this, args = arguments; function delayed () < if (!execAsap) func.apply(obj, args); timeout = null; >; if (timeout) clearTimeout(timeout); else if (execAsap) func.apply(obj, args); timeout = setTimeout(delayed, threshold || 100); >; > // smartresize jQuery.fn[sr] = function(fn)< return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); >; >)(jQuery,'smartresize'); // usage: $(window).smartresize(function()< // code that takes it easy. >); 

Источник

Window: resize event

The resize event fires when the document view (window) has been resized.

This event is not cancelable and does not bubble.

In some earlier browsers it was possible to register resize event handlers on any HTML element. It is still possible to set onresize attributes or use addEventListener() to set a handler on any element. However, resize events are only fired on the window object (i.e. returned by document.defaultView ). Only handlers registered on the window object will receive resize events.

While the resize event fires only for the window nowadays, you can get resize notifications for other elements using the ResizeObserver API.

If the resize event is triggered too many times for your application, see Optimizing window.onresize to control the time after which the event fires.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("resize", (event) => >); onresize = (event) => >; 

Event type

Event properties

This interface also inherits properties of its parent, Event . UIEvent.detail Read only Returns a long with details about the event, depending on the event type. UIEvent.sourceCapabilities Experimental Read only Returns an instance of the InputDeviceCapabilities interface, which provides information about the physical device responsible for generating a touch event. UIEvent.view Read only Returns a WindowProxy that contains the view that generated the event. UIEvent.which Deprecated Non-standard Read only Returns the numeric keyCode of the key pressed, or the character code ( charCode ) for an alphanumeric key pressed.

Examples

Window size logger

HTML

p>Resize the browser window to fire the code>resizecode> event.p> p>Window height: span id="height">span>p> p>Window width: span id="width">span>p> 

JavaScript

const heightOutput = document.querySelector("#height"); const widthOutput = document.querySelector("#width"); function reportWindowSize()  heightOutput.textContent = window.innerHeight; widthOutput.textContent = window.innerWidth; > window.onresize = reportWindowSize; 

Result

addEventListener equivalent

.addEventListener("resize", reportWindowSize); 

Specifications

Browser compatibility

Found a content problem with this page?

This page was last modified on Apr 8, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How to trigger the window resize event in JavaScript?

I have registered a trigger on window resize. I want to know how I can trigger the event to be called. For example, when hide a div, I want my trigger function to be called. I found window.resizeTo() can trigger the function, but is there any other solution?

10 Answers 10

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

jQuery’s trigger does not actually trigger the native «resize» event. It only triggers event listeners that have been added using jQuery. In my case, a 3rd party library was listening directly to the native «resize» event and this is the solution that worked for me.

Great and simple solution. Although, I think you should add some code for IE compatibility (as far as I see, for IE, we have to use window.fireEvent )

this didnt work on all devices for me. i had to trigger the event like this: var evt = document.createEvent(‘UIEvents’); evt.initUIEvent(‘resize’, true, false, window, 0); window.dispatchEvent(evt);

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); 

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); > 

Источник

Оцените статью