Skip to content

Instantly share code, notes, and snippets.

@woody180
Last active January 29, 2023 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woody180/eb7116d6a5b73cded9f63cf63b8eac54 to your computer and use it in GitHub Desktop.
Save woody180/eb7116d6a5b73cded9f63cf63b8eac54 to your computer and use it in GitHub Desktop.
Inline responsiveness
/*
* add attributes like in the example
* data-responsive="max-width[100]; style[color: ...; font-size: ...;]"
*/
document.querySelectorAll('[data-responsive]').forEach(elem => {
const str = elem.getAttribute('data-responsive');
const match = str.match(/max-width[\s+]?\[(.*?)\]\;/g);
const maxWidth = match[0].match(/\[(.*?)\]/)[1];
const styles = str.match(/style[\s+]?\[(.*?)\]/)[1];
let myFunction = x => {
if (x.matches) { // If media query matches
elem.setAttribute('style', styles);
} else {
elem.removeAttribute('style')
}
}
let x = window.matchMedia("(max-width: "+maxWidth+"px)");
myFunction(x);
x.addListener(myFunction);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment