function applyMediaQuery(selector, maxWidth) {
const elements = document.querySelectorAll(selector);
function updateClasses(mediaQuery) {
elements.forEach((item) => {
if (mediaQuery.matches) {
item.classList.add('mobile');
} else {
item.classList.remove('mobile');
}
});
}
const mediaQuery = window.matchMedia(`(max-width: ${maxWidth}px)`);
// Initial check
updateClasses(mediaQuery);
// Listen for changes
mediaQuery.addEventListener('change', updateClasses);
return elements;
}
// Usage
applyMediaQuery(".hero", 600);
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter