mediaQuery
a simple yet powerful mediaQuery
function that allows you to easily listen for media query changes and execute callbacks when conditions are met.
mediaQuery(query, callback);
mediaQuery("(max-width:800px)", (matches) => {
if (matches) {
$("aside").setClass("slideIn animated");
} else {
$("aside").setClass("slideOut animated");
}
})
Detect Mobile View (e.g., max-width: 768px)
mediaQuery("(max-width: 768px)", (matches) => {
if (matches) {
console.log("Mobile view activated! 📱");
} else {
console.log("Switched to Desktop 🖥️");
}
});
Apply Styles Dynamically
mediaQuery("(min-width: 1024px)", (matches) => {
document.body.style.backgroundColor = matches ? "lightblue" : "white";
});
Toggle Navigation Menu
mediaQuery("(max-width: 600px)", (isMobile) => {
document.getElementById("nav-menu").style.display = isMobile ? "none" : "block";
});
The mediaQuery
function supports any valid CSS media query, no matter how complex. it can handle:
✅ Basic queries:
(max-width: 600px)
(min-width: 768px) and (max-width: 1024px)
✅ Orientation:(orientation: portrait)
✅ Aspect ratio & resolution:(min-aspect-ratio: 16/9)
(min-resolution: 300dpi)
✅ Multiple conditions with OR/AND:(max-width: 800px) and (orientation: landscape)
(min-width: 1024px), (min-height: 768px)
Last updated