@cesarfernandoig/alpine-responsive-plugin
Version:
A lightweight Alpine.js plugin that simplifies managing conditional attributes in responsive designs.
46 lines (39 loc) • 1.78 kB
JavaScript
;
function changeAttributeValue(el, attribute, oldValue, newValue) {
if (attribute == "class") {
if (oldValue != null) el.classList.remove(...oldValue.split(" "));
if (newValue != null) el.classList.add(...newValue.split(" "));
} else {
if (newValue != null) el.setAttribute(attribute, newValue);
else if (el.hasAttribute(attribute)) el.removeAttribute(attribute);
}
}
/**
* Creates a custom Alpine.js directive that applies conditional attributes to elements
* based on whether the device is mobile or not.
*
* @param {import("./create-media-state").MediaState} mediaState - The media query state created by `createMediaState`.
* @returns {Function} - A function that defines the custom directive.
*/
export default (mediaState) =>
(el, { expression }, { evaluate, effect }) => {
// Effect that runs whenever the media query state changes.
effect(() => {
// Evaluates the expression to get the conditional attributes.
const mobileAttributes = evaluate(expression);
// If the device is mobile, apply the corresponding attributes or remove them.
if (mediaState.isMobile) {
for (const [attribute, value] of Object.entries(mobileAttributes)) {
const [mobileValue, desktopValue] = Array.isArray(value) ? value : [value, null];
changeAttributeValue(el, attribute, desktopValue, mobileValue);
}
}
// If the device is desktop, apply the corresponding attributes or remove them.
else if (mediaState.isDesktop) {
for (const [attribute, value] of Object.entries(mobileAttributes)) {
const [mobileValue, desktopValue] = Array.isArray(value) ? value : [value, null];
changeAttributeValue(el, attribute, mobileValue, desktopValue);
}
}
});
};