@cesarfernandoig/alpine-responsive-plugin
Version:
A lightweight Alpine.js plugin that simplifies managing conditional attributes in responsive designs.
35 lines (29 loc) • 1.09 kB
JavaScript
;
/**
* @typedef {Object} MediaState
* @property {boolean} isMobile
* @property {boolean} isDesktop
*/
/**
* Creates a reactive object representing the media query state.
* This object contains `isMobile` and `isDesktop` properties that automatically update
* when the screen size changes.
*
* @param {Object} Alpine - The Alpine.js instance.
* @returns {MediaState} - A reactive object with `isMobile` and `isDesktop` properties.
*/
export default function createMediaState(Alpine) {
// Defines a media query to detect if the screen is desktop (min-width: 768px).
const isDesktopQuery = window.matchMedia("(min-width: 768px)");
// Creates a reactive object with Alpine containing the media query state.
let media = Alpine.reactive({
isMobile: !isDesktopQuery.matches,
isDesktop: isDesktopQuery.matches,
});
// Listens for changes in the media query and updates the reactive state.
isDesktopQuery.addEventListener("change", (ev) => {
media.isMobile = !ev.matches;
media.isDesktop = ev.matches;
});
return media;
}