[FIXED] addEventListener resize not working
Solutions to fix common issues with resize event listeners. Plus, learn how to leverage the powerful 'ResizeObserver' API to observe changes in the dimensions of elements directly.
Jul 12, 2023 | Read time 10 minutes🔔 Table of contents
Introduction
Usually the “addEventListener” resize event will not be working is due to adding it to an element that is not “window”, having typos or not passing in the function reference correctly.
When I was developing a landing page builder app, a requirement was to preview the landing page in different window dimensions.
I though this would be a easy functionality to develop but found that I had some issues with the resize event.
In this post, I will show you my troubleshooting steps on how to get your “resize” event handler working correctly!
Generally to fix resize event handler issues we can go through the checklist:
- Make sure addEventListener is added to a “window” object
- Check event type spelling and case-sensitive
- Verify that we are passing the function reference
- Check removed event listeners
- Consider using ResizeObserver for DOM elements.
1. Make sure addEventListener is added to a “window” object
The most common mistake that I have found is that the resize event only triggers on the window
object!
It will not work with DOM elements - not even the document
object.
The addEventListener function in JavaScript is used to listen for specific events on a specific element. The ‘resize’ event is fired when the document view (window) has been resized.
A example of how to attach a handler to the window resize is like below:
// ✔️ Working!
window.addEventListener('resize', function() {
console.log('Window has been resized');
});
// ❌ This will not work since you will need to attach to the window object
document.addEventListener('resize', function() {
// Will never work!
});
You may need to add this after the DOMContentLoaded event if you have elements that are only available after a DOM load.
document.addEventListener('DOMContentLoaded', function() {
window.addEventListener('resize', function() {
// Execute code and access to your DOM elements here...
});
});
2. Check event type spelling and case-sensitive
On thing that has tripped me up in the past is not typing “resize” correctly.
When you are calling the addEventListener, the first parameter is the event type. Now this is required and is case-sensitive. So “Resize” will not work (eg capital “R”)
The syntax will look like this:
addEventListener(type, listener, options)
- type is a string of a “event type” and case-sensitive. So this means that ‘Click’ (and will not work) is different to ‘click’. You can see all possible event types here: Events
- listener is a function reference.
A common way to use “addEventListener” is as follows:
let button = document.querySelector('#myButton');
button.addEventListener('click', function() {
console.log('Button clicked!');
});
3. Verify that we are passing the function reference
Another problem that has got me sometime is passing in a function “call” instead of a function reference.
So what does this mean??
When you CALL function - this just means that you are telling JavaScript run the code inside that function.
This is done by writing out the function name followed by parentheses.
Now as for the function reference - this means that your function can act like a parameter (without the parentheses).
Here is an example error I recently had that did not work:
// ❌ Will not work since its a function call
window.addEventListener('resize', setSize());
function setSize(){
width = window.innerWidth;
console.log(width);
}
Due to the use of parentheses (()
) - in the above code, we are telling Javascript to execute our function (setSize()
) immediately!
To fix this, we just need to remove the parentheses. So this means that addEventListener
will trigger our function when the “resize” event happens.
// ✔️ Will not work since its a function call
window.addEventListener('resize', setSize);
function setSize(){
width = window.innerWidth;
console.log(width);
}
4. Check removed event listeners
One issue that could be tricky to track down when you find that resize is not working is that you have removed the event listener somewhere else in your code base.
In order to remove an event listener, you need to pass the exact function reference to removeEventListener that you passed to addEventListener.
// Create a specific function to handle the event
function handleResize() {
// do something here
}
// Add the event listener
window.addEventListener('resize', handleResize);
...
...
// Later, you can remove the event listener
window.removeEventListener('resize', handleResize);
In the above example we have a “handleResize” function whenever the window resize happens.
However, somewhere later in our code base, we use removeEventListener to remove the handleResize function from the list of event listeners on the ‘resize’ event.
Memory management tip
One thing to keep in mind is that anonymous functions (functions declared inline when you call addEventListener) cannot be removed with removeEventListener because you do not have a reference to the function.
So the function will linger around in memory until gets to the garbage collector.
It is best practice to first declare the event handler function and pass it as parameters for
addEventListener
andremoveEventListener
As an example, the following will not remove the event handler due to use of anonymous functions:
// Add the event listener
window.addEventListener('resize', function() {
console.log('Window has been resized');
});
// This will not work, because the function in removeEventListener is not the same function as in addEventListener
window.removeEventListener('resize', function() {
console.log('Window has been resized');
});
👉 onresize vs resize
If you are using the onresize
property, you will need to have further considerations.
You can only have one handler if you are using this onresize
property.
Consider the following code:
// This sets up an event listener for the resize event
window.onresize = function() {
console.log('Window has been resized - first function');
};
// assign second function to the onresize property
window.onresize = function() {
console.log('Window has been resized - second function');
};
Now in the above code, only the second function will be able to execute - since this function will overwrite the first function!
The benefit using addEventListener
multiple times for the same event on the same object, they will all work.
However, with using the onresize
property, you have to be careful not to overwrite previous event listeners.
5. Consider using ResizeObserver for DOM elements.
If your requirement is to get a trigger on the resize of DOM element instead of the actual window, then consider using ResizeObserver
.
ResizeObserver can come with performance cost to your app if you have lots of DOM elements to observe, so use this carefully!
The ResizeObserver API provides a way to get notified whenever an element’s size changes.
This can be useful for things like adjusting layout in response to elements changing size, or updating other UI elements when a resize occurs.
Here is a basic example of how to use it:
// create a new instance of ResizeObserver
let resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
console.log('Element:', entry.target);
console.log('Element size:', entry.contentRect);
console.log(`Resized: New width: ${entry.contentRect.width},
New height: ${entry.contentRect.height}`);
}
});
// Start observing an element
let elementToObserve = document.querySelector('.some-element');
resizeObserver.observe(elementToObserve);
In the example above, entries is an array of ResizeObserverEntry objects, each of which represents a single observed box.
The contentRect
property gives you access to the new dimensions of the box.
You can also stop observing the DOM element with the unobserve
function:
let elementToObserve = document.querySelector('.some-element');
// resizeObserver.unobserve(elementToObserve);
Compatibility with ResizeObserver
- only available with modern versions of browsers
- not supported in Internet Explorer
- Safari versions 13 and under is not supported
Summary
In this post, I went through some troubleshooting tips and checklist on how to fix resize event not working.
Generally this is due to attaching the addEventListener to a object that is not the window object. The resize only triggers on window resize!
Other causes for this issue is that there could be spelling or case-sensitivity of the event type, passing in the function call instead of a reference or that the event is removed in another area of the code base.
Now if we want to check resize on a DOM element, we can use the power and utility of the ‘ResizeObserver’ API. We can use it to observe changes in the dimensions of DOM elements directly.