0

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.

user1406440
  • 1,329
  • 2
  • 24
  • 59

1 Answers1

1

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.

Yan Esteves
  • 98
  • 1
  • 1
  • 5
  • Thanks this worked great! I'm sure I accepted this answer but it looked as though it had vanished yesterday. Back now though so I've marked again! :D – user1406440 Dec 24 '22 at 10:50