I have a function which must be executed immediately then in an eventListener.
Here is how I run both:
function mediaBodyClass() {
var body = document.body;
if (window.innerWidth >= 992) {
body.classList.add('desktop');
body.classList.remove('mobile');
} else {
body.classList.add('mobile');
body.classList.remove('desktop');
}
};
mediaBodyClass(); // Now
// In the listener
window.addEventListener('resize', function() {
mediaBodyClass();
});
What is the best practice?
You can use a media query to apply styles to the body when the screen width is smaller than a certain limit, instead of using JavaScript:
body{
/* .desktop styles go here */
}
@media only screen and (max-width: 992px) {
body {
/* .mobile styles go here */
}
}
Whilst what you are doing is fine - you might find the matchMedia api useful - basically its a javascript version of a media query in which you can attach functions to given viewport widths and also listen for changes to the viewport size.
Here is a link to a useful article.https://css-tricks.com/working-with-javascript-media-queries/
const mediaQuery = window.matchMedia('(min-width: 992px)')
function handleViewportSizeChange(e) {
var body = document.body;
if (e.matches) {
body.classList.add('desktop');
body.classList.remove('mobile');
}else {
body.classList.add('mobile');
body.classList.remove('desktop');
}
}
// Register event listener
mediaQuery.addListener(handleViewportSizeChange)
// Initial check
handleViewportSizeChange(mediaQuery)