VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-add-or-remove-classes-on-resize-with-jquery/

⇱ How to Add or Remove Classes on Resize with jQuery ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Add or Remove Classes on Resize with jQuery ?

Last Updated : 12 Nov, 2024

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


Explanation:

  1. Event Binding:
    • $(window).resize() attaches an event listener to the window's resize event, so the handleResize() function is executed whenever the window is resized.
  2. 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-screen is added, and large-screen is removed.
    • If the window's width is 600 pixels or more, the opposite happens (large-screen is added, and small-screen is removed).
  3. 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:


This ensures that handleResize() is called only once every 200 milliseconds during a resize event, preventing excessive calls to the function

Comment
Article Tags: