@cesarfernandoig/alpine-responsive-plugin
Version:
A lightweight Alpine.js plugin that simplifies managing conditional attributes in responsive designs.
2 lines (1 loc) • 900 B
JavaScript
(()=>{function c(e){let t=window.matchMedia("(min-width: 768px)"),i=e.reactive({isMobile:!t.matches,isDesktop:t.matches});return t.addEventListener("change",s=>{i.isMobile=!s.matches,i.isDesktop=s.matches}),i}var m=e=>()=>(t,i=null)=>e.isMobile?t:i;function f(e,t,i,s){t=="class"?(i!=null&&e.classList.remove(...i.split(" ")),s!=null&&e.classList.add(...s.split(" "))):s!=null?e.setAttribute(t,s):e.hasAttribute(t)&&e.removeAttribute(t)}var d=e=>(t,{expression:i},{evaluate:s,effect:b})=>{b(()=>{let u=s(i);if(e.isMobile)for(let[o,r]of Object.entries(u)){let[a,l]=Array.isArray(r)?r:[r,null];f(t,o,l,a)}else if(e.isDesktop)for(let[o,r]of Object.entries(u)){let[a,l]=Array.isArray(r)?r:[r,null];f(t,o,a,l)}})};function n(e){let t=c(e);e.magic("media",()=>t),e.magic("getMobileValue",m(t)),e.directive("mobileattributes",d(t))}document.addEventListener("alpine:init",()=>window.Alpine.plugin(n));})();