Sharing the CSS breakpoints with JavaScript

šŸ“– 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!

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!


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

Neural Networks for JavaScript developers
Presale - 15$ free coupon

Hi friend! Before you go, just wanted to let you know that in March 2023 I will be launching the TensorFlow.Js by Example course.

This course will include basic concepts of AI and Neural Networks done with TensorFlowJs such as:

  • Working with datasets
  • Visualizing training
  • Deep Neural Networks in JavaScript
  • Reinforcement Learning
  • Convolutional neural networks
  • and much more ...

Also, there will be a lot of examples as:

  • Object detection
  • Natural language processing
  • Face and voice recognition
  • Gaming AI

Join now the waiting list and get a 15$ coupon off the launching price!

X