Last active
January 29, 2023 17:02
-
-
Save woody180/eb7116d6a5b73cded9f63cf63b8eac54 to your computer and use it in GitHub Desktop.
Inline responsiveness
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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