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

Time:12-23

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.

CodePudding user response:

To achieve this, you can use the window.matchMedia method to check the current screen width, and then use the remove method of the classList property to remove the cart-toggled class if necessary.

Here's an example of how you could modify your code to do this:

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

const handleToggleClick = e => {
  e.preventDefault();
  cart.classList.toggle('cart-toggled');
};

const handleResize = () => {
  if (window.matchMedia(`(min-width: Xpx)`).matches) {
    cart.classList.remove('cart-toggled');
  }
};

toggle.addEventListener('click', handleToggleClick);
window.addEventListener('resize', handleResize);

In this example, X should be replaced with the minimum width at which you want the toggle behavior to be disabled.

The handleResize function is called every time the window is resized, and it uses window.matchMedia to check if the current screen width is greater than or equal to Xpx. If it is, it removes the cart-toggled class from the cart element.

Note that this will only remove the cart-toggled class if it is already applied, so it won't interfere with the toggle behavior when the screen width is below the threshold.

  • Related