Found an interesting technique that allows sharing the CSS breakpoints with the Javascript code. Basically, we want to be able to know in the Javascript code when a CSS media query becomes active.
In order to put it into practice, we will use the before
pseudo-element and a resize listener.
First, use the content
of before
combined with the standard media queries to describe what type of device we are on:
body:before {
content: "smartphone";
display: none; /* Prevent from displaying. */
}
@media (min-width: 700px) {
body:before {
content: "tablet";
}
}
@media (min-width: 1100px) {
body:before {
content: "desktop";
}
}
After just read that content
in a resize lister so that we will know in Javascript what is the screen size:
window.addEventListener('resize', () => {
const screenType = window.getComputedStyle(document.querySelector('body'), ':before').getPropertyValue('content').replace(/\"/g, ''); };
if (screenType == 'tablet') {
console.log('Tablet breakpoint');
}
// more breakpoints here
}
Found it in this older article written by Mike Herchel. He goes into more detail about the implementation in the article.
Or course more direct way is to have the breakpoints values both in CSS and Javascript, but this means we will need to make changes in two files when we want to modify something.
š Neural networks for Javascript developers
The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!