Category Archives: English

How to accurately detect responsive breakpoints

How to accurately detect responsive breakpoints

I recently had to detect in Javascript which responsive “state” a page was rendered. For instance, I had to detect that it was rendering the mobile phone state, which was the @media(max-width: 767px) breakpoint in CSS.

I wanted to do it with $(document).width(), but sadly, the jQuery width() method didn’t return the correct width of the screen, because it wasn’t counting the scrollbar, but CSS is.

The problem with scrollbars

The scrollbar is an OS and often theme-specific GUI element. It has not a fixed, concensual width. And unfortunately, $(document).width() does not take the scrollbar width into account.

We could use some hacks like $(document).width() + any_amount, but it would not work correctly because scrollbars don’t have the same width everywere. Some screen widths would end up in an incoherent state. See this JSFiddle for an example.

The solution : use CSS to detect the breakpoints

I found out this little hack and though it would be interesting to share. Instead of using $(document).width(), we should use the @media query somehow to get the responsive “state” of the CSS. This way, we cannot be wrong.

A simple CSS rule and a hidden div can do the trick :

<div class="responsive-state">
</div>
.responsive-state {
    display:none;
    width: 10000px;
}
@media (max-width: 767px) {
    .responsive-state {
        width: 767px;
    }
}
@media (min-width: 768px) and (max-width: 1024px) {
    .responsive-state {
        width: 1024px;
    }
}
function responsive_state()
{
    return $('.responsive-state').css('width');
}

A demo can be found here on JSFiddle.

For each responsive breakpoint, its maximum width is set as the width of .responsive-state. This way, calling responsive_state() will always return a different width for each responsive “state”. Using this value, you can detect the responsive state accurately. You don’t have incoherent state anymore.