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.
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 instrict mode
.The
addEvent
function provided by @Alex V does not return theevent object
if theaddEventListener
method is used. Another parameter should be added to theaddEvent
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:An example call to the new
addEvent
function:The following blog post may be useful to you: Fixing the window resize event in IE
It provides this code:
jQuery is just wrapping the standard
resize
DOM event, eg.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.
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 objecttype
: resize, scroll (event type)callback
: the function referenceThen use is like this:
or with an anonymous function:
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:
Note that a child element can call
on the event object that is passed in as the first Arg of the resize event. For example: