javascripthtmlcssmatchmedia

Remove class (if present) when screen width is greater than 1024px


On mobile I have 2 panels/draws that are the width of the viewport (side by side). There is a link to toggle which one is in view and when clicked, this slides the panels left/right.

However on desktop, this isn't needed as they are both in view. So if the screen width exceeds 'x' I'd like the remove this .cart__toggled class. As on resize it screws to the UI.

This is my current code which toggles the classes to move the relevant panels in/out of view:

const cart = document.querySelector('.cart');
const toggle = document.querySelector('.cart__toggle');

toggle.addEventListener('click', e => {
   e.preventDefault();
   cart.classList.toggle('cart-toggled');
});

So in short the 'logic' would be 'if screen width is greater that x', 'if the class .cart-toggled is applied to .cart, remove it'. It doesn't need to re apply it when reducing the with of the browser.


Solution

  • You can use the 'window.matchMedia' method to check the screen width and then use the remove property method.

    An example would be:

    const cart = document.querySelector('.cart');
    const toggle = document.querySelector('.cart__toggle');
    
    toggle.addEventListener('click', e => {
       e.preventDefault();
       cart.classList.toggle('cart-toggled');
    });
    
    // Removes the .cart-toggled class when the screen is resized.
    window.addEventListener('resize', e => {
       if (window.matchMedia(`(min-width: Xpx)`).matches) {
         cart.classList.remove('cart-toggled');
       }
    });
    

    In the above example, X must be replaced with the pixel you want as min-width. And the handleResize function will be called whenever the screen width changes.