JavaScript onresize
Event: Detecting Window Resizing
The JavaScript onresize
event is a fundamental part of creating responsive web applications. It triggers whenever the browser window is resized, allowing you to dynamically adjust your page layout, content, and functionality based on the current viewport dimensions. This event is crucial for providing a seamless user experience across various screen sizes and devices.
What is the onresize
Event?
The onresize
event is a browser event that fires on the window
object whenever the user resizes the browser window, or changes the device orientation that leads to resize. It is a key component of responsive web design, enabling developers to:
- Dynamically adjust layouts to fit different screen sizes.
- Modify content based on available space.
- Optimize performance for different viewports.
- Create responsive graphics using
<canvas>
or other elements.
Purpose of the onresize
Event
The main purpose of the onresize
event is to enable real-time adaptation of your website or application to changes in the user’s viewing environment. It empowers you to:
- React to users resizing their browser windows.
- Adjust to various devices (desktops, tablets, phones) and orientations.
- Maintain visual consistency and usability across diverse screens.
Syntax of the onresize
Event
The onresize
event can be attached to the window
object in several ways, using either inline HTML attributes or JavaScript event listeners:
HTML Attribute:
<body onresize="myFunction()">
<!-- Your content here -->
</body>
JavaScript Event Listener:
window.onresize = function() {
// Your code here
};
// Alternatively using addEventListener
window.addEventListener('resize', function() {
// Your code here
});
Property/Method | Type | Description |
---|---|---|
`onresize` | Event Handler | An event handler property that directly assigns a JavaScript function to be called when the window is resized. |
`addEventListener(‘resize’, function)` | Method | Adds a listener function to the window object. The listener function will be called when the window is resized. More than one listener function can be added using this method |
`removeEventListener(‘resize’, function)` | Method | Removes the listener added before, using the same function reference. |
`window.innerWidth` | Property | Returns the inner width of the windowβs content area (viewport) in pixels, excluding scrollbars, toolbars and window borders. |
`window.innerHeight` | Property | Returns the inner height of the window’s content area (viewport) in pixels, excluding scrollbars, toolbars and window borders. |
Basic Examples of Using onresize
Event
Let’s look at some basic examples to understand how to utilize the onresize
event effectively.
Simple Alert on Resize
This first example demonstrates the most basic use of the onresize
event by displaying an alert message when the window is resized.
<body style="height: 200px;">
<p>Resize the browser window to see the alert.</p>
<script>
window.onresize = function() {
alert("Window resized!");
};
</script>
</body>
Output:
When you resize the browser window, an alert box will appear saying “Window resized!”. This confirms that the onresize
event handler is working correctly.
Displaying Window Dimensions
This example shows how to access and display the current window dimensions (width and height) upon resizing. It updates the content of two HTML elements showing inner width and inner height of the window.
<body style="height: 200px;">
<p>Window Inner Width: <span id="widthDisplay"></span> pixels</p>
<p>Window Inner Height: <span id="heightDisplay"></span> pixels</p>
<script>
const widthDisplay = document.getElementById("widthDisplay");
const heightDisplay = document.getElementById("heightDisplay");
function displayWindowSize() {
widthDisplay.textContent = window.innerWidth;
heightDisplay.textContent = window.innerHeight;
}
window.addEventListener('resize', displayWindowSize);
// Initial display
displayWindowSize();
</script>
</body>
Output:
Initially, the window’s width and height will be displayed. As you resize the window, these values will dynamically update, showing the current viewport dimensions. This is extremely helpful to show responsive layouts or graphics on resizing.
Adjusting Text Size on Resize
This example demonstrates how to dynamically adjust the font size of a text element based on the window width. It also show how to use removeEventListener
.
<body style="height: 200px;">
<p id="resizeText" style="font-size: 16px;">
This text will change its size when the window is resized.
</p>
<button id="removeButton">Remove Resize Listener</button>
<script>
const resizeTextElement = document.getElementById("resizeText");
const removeButtonElement = document.getElementById("removeButton");
function adjustFontSize() {
const windowWidth = window.innerWidth;
if (windowWidth < 600) {
resizeTextElement.style.fontSize = "14px";
} else if (windowWidth < 1000) {
resizeTextElement.style.fontSize = "18px";
} else {
resizeTextElement.style.fontSize = "24px";
}
}
window.addEventListener('resize', adjustFontSize);
// Initial adjustment
adjustFontSize();
removeButtonElement.addEventListener('click', function() {
window.removeEventListener('resize', adjustFontSize);
alert('Resize listener has been removed. Text will not resize now.');
});
</script>
</body>
Output:
The text’s font size will change as you resize the browser window, decreasing for smaller widths and increasing for larger ones. This provides an example of how the onresize
event can be used to adapt the visual style of the content on your webpage.
Advanced Use Cases of the onresize
Event
The onresize
event is not just for simple adjustments, but also serves to handle complex layout changes and dynamic rendering.
Dynamic Canvas Rendering
This example illustrates how to redraw a canvas element with different content based on the window size. This involves drawing a circle with a different radius based on the window’s inner width.
<canvas
id="dynamicCanvas"
width="300"
height="200"
style="border: 1px solid #ddd;"
></canvas>
<script>
const dynamicCanvasElement = document.getElementById("dynamicCanvas");
const ctx_dynamic = dynamicCanvasElement.getContext("2d");
function drawCircle() {
const windowWidth = window.innerWidth;
const radius = Math.min(windowWidth / 8, 80);
// Clear canvas
ctx_dynamic.clearRect(0, 0, dynamicCanvasElement.width, dynamicCanvasElement.height);
// Draw circle
ctx_dynamic.beginPath();
ctx_dynamic.arc(
dynamicCanvasElement.width / 2,
dynamicCanvasElement.height / 2,
radius,
0,
2 * Math.PI
);
ctx_dynamic.fillStyle = "purple";
ctx_dynamic.fill();
}
window.addEventListener('resize', drawCircle);
// Initial Draw
drawCircle();
</script>
Output:
As you resize the window, the circle on the canvas will adjust its size dynamically based on the current browser width, showcasing the dynamic rendering capabilities of canvas using the onresize
event.
Managing Multiple Elements on Resize
This example will demonstrate changing the number of colored boxes on resize. The number of boxes displayed will change based on different window widths.
<div id="boxContainer" style="display: flex; flex-wrap: wrap;"></div>
<script>
const boxContainerElement = document.getElementById("boxContainer");
function generateBoxes() {
const windowWidth = window.innerWidth;
let numberOfBoxes;
if (windowWidth < 600) {
numberOfBoxes = 3;
} else if (windowWidth < 1000) {
numberOfBoxes = 6;
} else {
numberOfBoxes = 9;
}
boxContainerElement.innerHTML = ""; // Clear existing boxes
for (let i = 0; i < numberOfBoxes; i++) {
const box = document.createElement("div");
box.style.width = "80px";
box.style.height = "80px";
box.style.margin = "5px";
box.style.backgroundColor = `hsl(${i * (360 / numberOfBoxes)}, 100%, 50%)`;
boxContainerElement.appendChild(box);
}
}
window.addEventListener('resize', generateBoxes);
// Initial box generation
generateBoxes();
</script>
Output:
As you resize the window, the number of colored boxes will change, ensuring that the layout of the boxes adapts to different screen sizes.
Tips and Best Practices for onresize
Event
- Debouncing: Implement debouncing to avoid excessive function calls during continuous resizing, which can impact performance.
- Performance: Avoid heavy computations directly within the
onresize
handler. Instead, trigger animations or rendering updates as needed. - Layout Shifts: Be mindful of potential layout shifts during resizing, which can negatively affect the user experience.
- Mobile Testing: Always test your designs on different mobile devices and orientations, since orientation change also triggers the
onresize
event. requestAnimationFrame
: When handling animations within theonresize
event, consider usingrequestAnimationFrame
for smoother rendering.
Browser Support
The onresize
event is supported by all modern browsers, including:
- Chrome
- Firefox
- Safari
- Edge
- Opera
This wide compatibility ensures a consistent behavior of the event handler across all major platforms. π
Conclusion
The JavaScript onresize
event is a vital tool for creating responsive and adaptive web applications. By understanding how to use this event, you can build dynamic and engaging user interfaces that adjust seamlessly to various screen sizes and devices. The practical examples in this article serve as an excellent starting point for using this event to create better web user experiences. Always remember the best practices and tips to optimize performance while using this useful event.