Created
October 21, 2022 17:55
-
-
Save Mao8a/a431684e05a8c33b412e6fbb7cfd17fe to your computer and use it in GitHub Desktop.
Use css media queries as JavaScrip variables based on a DOM element
This file contains 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
<script> | |
/** | |
* @description Encapsule all variables and funtions | |
* @const mediaQueryHTML {Object} New DOM element with css heigth based on css break points | |
*/ | |
(function () { | |
const mediaQueryHTML = document.createElement('div'); | |
const breakPoints = { | |
0: 1, //xxs | |
1: 2, //xs | |
2: 3, //s | |
3: 4, //m | |
4: 5, //l | |
5: 6, //xl | |
}; | |
mediaQueryHTML.className = 'media-query-js'; | |
/** | |
* @description Main function | |
* Set max items based on breakpoints | |
*/ | |
function onDocumentReady() { | |
document.querySelector('body').appendChild(mediaQueryHTML); | |
const breakPoint = mediaQueryHTML.offsetHeight; | |
const maxItems = breakPoints[breakPoint]; | |
console.log(maxItems); | |
} | |
document.readyState !== 'loading' ? onDocumentReady() | |
: document.addEventListener('DOMContentLoaded', onDocumentReady); | |
})(); | |
</script> | |
<style> | |
/* Media query js */ | |
.media-query-js { | |
position: absolute; | |
z-index: -1; | |
height: 0; | |
width: 0; | |
} | |
/* @include breakpoint(xs-up) { */ | |
@media (max-width: 375px) { | |
.media-query-js { | |
height: 1px; | |
} | |
} | |
/* @include breakpoint(s-up) { */ | |
@media (max-width: 480px) { | |
.media-query-js { | |
height: 2px; | |
} | |
} | |
/* @include breakpoint(m-up) { */ | |
@media (max-width: 768px) { | |
.media-query-js { | |
height: 3px; | |
} | |
} | |
/* @include breakpoint(l-up) { */ | |
@media (max-width: 1024px) { | |
.media-query-js { | |
height: 4px; | |
} | |
} | |
/* @include breakpoint(xl-up) { */ | |
@media (max-width: 1440px) { | |
.media-query-js { | |
height: 5px; | |
} | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment