7

Sharing the CSS breakpoints with JavaScript

 3 years ago
source link: http://www.js-craft.io/blog/sharing-the-css-breakpoints-with-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Sharing the CSS breakpoints with JavaScript

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
}

Fond 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.

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.

Newsletter subscribe:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK