简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM