How can I hook into a browser window resize event?
There's a jQuery way of listening for resize events but I would prefer not to bring it into my project for just this one requirement.
How can I hook into a browser window resize event?
There's a jQuery way of listening for resize events but I would prefer not to bring it into my project for just this one requirement.
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.
window.addEventListener('resize', function(){}, true);
–
Anodic addEventListener
instead so your script doesn't break other scripts on the page. –
Chesterfieldian window.onresize = () => { /* code */ };
or better: window.addEventListener('resize', () => { /* code */ });
–
Pearson true
? –
Loganiaceous First off, I know the addEventListener
method has been mentioned in the comments above, but I didn't see any code. Since it's the preferred approach, here it is:
window.addEventListener('resize', function(event){
// do stuff here
});
removeEventListener
. –
Chesterfieldian window.addEventListener('resize', onResize)
and add window.removeEventListener('resize', onResize)
like @StijndeWitt suggested. –
Phosphorous Never override the window.onresize function.
Instead, create a function to add an Event Listener to the object or element. This checks and incase the listeners don't work, then it overrides the object's function as a last resort. This is the preferred method used in libraries such as jQuery.
object
: the element or window object
type
: resize, scroll (event type)
callback
: the function reference
var addEvent = function(object, type, callback) {
if (object == null || typeof(object) == 'undefined') return;
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on"+type] = callback;
}
};
Then use is like this:
addEvent(window, "resize", function_reference);
or with an anonymous function:
addEvent(window, "resize", function(event) {
console.log('resized');
});
attachEvent
is no longer supported. The preferred way for the future is addEventListener
. –
Phinney elem == undefined
. It is possible (although unlikely) that "undefined" is locally defined as something else. #8176173 –
Phinney addEvent
function allow for the return of the event
object. In your example, your anonymous function is expecting the event
object, while the addEventListener
method you use within addEvent
does not return it. You should add a parameter: addEvent = function(object, type, callback, **eventReturn**)
and use this new parameter in your addEventListenerCall
: object.addEventListener(type, callback, **eventReturn**);
–
Anodic object
as a variable name. The function you have provided will not work in strict mode. I would suggest changing the parameter object
of your addEvent
function to "obj" instead. –
Anodic object
is not a reserved keyword. Object
on the other hand is a built in function, so its still save to use. –
Maccabean addEvent
implementation. To be honest, I wouldn't use it anymore. Just use addEventListener
. The few legacy browsers that did not support it have been laid to rest and support is now pretty much universal. –
Chesterfieldian object["on"+type] = callback;
statement, shouldn't you const previousCallback = object["on"+type] || () => {};
then set object["on"+type] = () => { previousCallback(); callback(); }
? May want to be mindful of avoiding arrow functions incase use of the this
keyword is being used.. –
Niklaus Solution for 2018+:
You should use ResizeObserver. It is a browser-native solution that has a much better performance than to use the resize
event. In addition, it not only supports the event on the document
but also on arbitrary elements
.
var ro = new ResizeObserver( entries => { for (let entry of entries) { const cr = entry.contentRect; console.log('Element:', entry.target); console.log(`Element size: ${cr.width}px x ${cr.height}px`); console.log(`Element padding: ${cr.top}px ; ${cr.left}px`); } }); // Observe one or multiple elements ro.observe(someElement);
Currently, Firefox, Chrome, Safari, and Edge support it. For other (and older) browsers you have to use a polyfill.
addEventListener
you only watch the element you are interrested in and with ResizeObserver
you watch everything, so I wonder how it can be more performant. Also addEventListener
seems more readable, if you are watching only one element, than looping and finding the good one (should it have an id). Am I missing something ? –
Tyratyrannical The resize event should never be used directly as it is fired continuously as we resize.
Use a debounce function to mitigate the excess calls.
window.addEventListener('resize',debounce(handler, delay, immediate),false);
Here's a common debounce floating around the net, though do look for more advanced ones as featuerd in lodash.
const debounce = (func, wait, immediate) => {
var timeout;
return () => {
const context = this, args = arguments;
const later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
This can be used like so...
window.addEventListener('resize', debounce(() => console.log('hello'),
200, false), false);
It will never fire more than once every 200ms.
For mobile orientation changes use:
window.addEventListener('orientationchange', () => console.log('hello'), false);
Here's a small library I put together to take care of this neatly.
(...arguments) => {...}
(or ...args
for less confusion) as the arguments
variable is no longer available their scope. –
Gradualism I do believe that the correct answer has already been provided by @Alex V, yet the answer does require some modernization as it is over five years old now.
There are two main issues:
Never use object
as a parameter name. It is a reservered word. With this being said, @Alex V's provided function will not work in strict mode
.
The addEvent
function provided by @Alex V does not return the event object
if the addEventListener
method is used. Another parameter should be added to the addEvent
function to allow for this.
NOTE: The new parameter to addEvent
has been made optional so that migrating to this new function version will not break any previous calls to this function. All legacy uses will be supported.
Here is the updated addEvent
function with these changes:
/*
function: addEvent
@param: obj (Object)(Required)
- The object which you wish
to attach your event to.
@param: type (String)(Required)
- The type of event you
wish to establish.
@param: callback (Function)(Required)
- The method you wish
to be called by your
event listener.
@param: eventReturn (Boolean)(Optional)
- Whether you want the
event object returned
to your callback method.
*/
var addEvent = function(obj, type, callback, eventReturn)
{
if(obj == null || typeof obj === 'undefined')
return;
if(obj.addEventListener)
obj.addEventListener(type, callback, eventReturn ? true : false);
else if(obj.attachEvent)
obj.attachEvent("on" + type, callback);
else
obj["on" + type] = callback;
};
An example call to the new addEvent
function:
var watch = function(evt)
{
/*
Older browser versions may return evt.srcElement
Newer browser versions should return evt.currentTarget
*/
var dimensions = {
height: (evt.srcElement || evt.currentTarget).innerHeight,
width: (evt.srcElement || evt.currentTarget).innerWidth
};
};
addEvent(window, 'resize', watch, true);
window.onresize = function() {
// your code
};
The following blog post may be useful to you: Fixing the window resize event in IE
It provides this code:
Sys.Application.add_load(function(sender, args) { $addHandler(window, 'resize', window_resize); }); var resizeTimeoutId; function window_resize(e) { window.clearTimeout(resizeTimeoutId); resizeTimeoutId = window.setTimeout('doResizeCode();', 10); }
The already mentioned solutions above will work if all you want to do is resize the window and window only. However, if you want to have the resize propagated to child elements, you will need to propagate the event yourself. Here's some example code to do it:
window.addEventListener("resize", function () {
var recResizeElement = function (root) {
Array.prototype.forEach.call(root.childNodes, function (el) {
var resizeEvent = document.createEvent("HTMLEvents");
resizeEvent.initEvent("resize", false, true);
var propagate = el.dispatchEvent(resizeEvent);
if (propagate)
recResizeElement(el);
});
};
recResizeElement(document.body);
});
Note that a child element can call
event.preventDefault();
on the event object that is passed in as the first Arg of the resize event. For example:
var child1 = document.getElementById("child1");
child1.addEventListener("resize", function (event) {
...
event.preventDefault();
});
You can use following approach which is ok for small projects
<body onresize="yourHandler(event)">
function yourHandler(e) {
console.log('Resized:', e.target.innerWidth)
}
<body onresize="yourHandler(event)">
Content... (resize browser to see)
</body>
<script language="javascript">
window.onresize = function() {
document.getElementById('ctl00_ContentPlaceHolder1_Accordion1').style.height = '100%';
}
</script>
var EM = new events_managment();
EM.addEvent(window, 'resize', function(win,doc, event_){
console.log('resized');
//EM.removeEvent(win,doc, event_);
});
function events_managment(){
this.events = {};
this.addEvent = function(node, event_, func){
if(node.addEventListener){
if(event_ in this.events){
node.addEventListener(event_, function(){
func(node, event_);
this.events[event_](win_doc, event_);
}, true);
}else{
node.addEventListener(event_, function(){
func(node, event_);
}, true);
}
this.events[event_] = func;
}else if(node.attachEvent){
var ie_event = 'on' + event_;
if(ie_event in this.events){
node.attachEvent(ie_event, function(){
func(node, ie_event);
this.events[ie_event]();
});
}else{
node.attachEvent(ie_event, function(){
func(node, ie_event);
});
}
this.events[ie_event] = func;
}
}
this.removeEvent = function(node, event_){
if(node.removeEventListener){
node.removeEventListener(event_, this.events[event_], true);
this.events[event_] = null;
delete this.events[event_];
}else if(node.detachEvent){
node.detachEvent(event_, this.events[event_]);
this.events[event_] = null;
delete this.events[event_];
}
}
}
© 2022 - 2024 — McMap. All rights reserved.