To add or remove classes when the window is resized using jQuery, you can use the $(window).resize() event to check the window size and conditionally add or remove classes. Here's how you can do it:
Example: Adding/Removing Classes on Window Resize
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Resize Example</title>
<style>
.small-screen {
background-color: lightcoral;
color: white;
}
.large-screen {
background-color: lightseagreen;
color: white;
}
#myElement {
padding: 20px;
margin: 20px;
text-align: center;
}
</style>
<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="myElement">Resize the window to see class changes</div>
<script>
$(document).ready(function() {
// Function to handle adding/removing classes on resize
function handleResize() {
const $element = $('#myElement');
if ($(window).width() < 600) {
$element.addClass('small-screen').removeClass('large-screen');
} else {
$element.addClass('large-screen').removeClass('small-screen');
}
}
// Initial check
handleResize();
// Bind the function to the window resize event
$(window).resize(function() {
handleResize();
});
});
</script>
</body>
</html>
Explanation:
- Event Binding:
$(window).resize()attaches an event listener to the window's resize event, so thehandleResize()function is executed whenever the window is resized.
- Adding/Removing Classes:
- Inside the
handleResize()function, the window's width is checked using$(window).width(). - If the window's width is less than 600 pixels, the class
small-screenis added, andlarge-screenis removed. - If the window's width is 600 pixels or more, the opposite happens (
large-screenis added, andsmall-screenis removed).
- Inside the
- Initial Call:
handleResize()is called immediately when the page loads to ensure that the correct classes are applied based on the initial window size.
Customization:
- You can change the conditions (e.g., different pixel widths) to suit your needs.
- You can add more conditions or classes based on your requirements.
Debouncing for Performance Optimization:
If you expect frequent resizing (e.g., when users resize the browser window), you might want to debounce the resize function to improve performance:
function debounce(func, delay) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(func, delay);
};
}
$(window).resize(debounce(handleResize, 200));
This ensures that handleResize() is called only once every 200 milliseconds during a resize event, preventing excessive calls to the function