Lifehack: Aligning Your CSS & JS Breakpoints

by Gennie Harris

If you're like me, you've hit a wall before where CSS falls just a little short of what you want to accomplish with your responsive design. And like me, perhaps you turned to jQuery to tweak things slightly when users visit your site on certain screen sizes. The general setup seems straightforward enough: wrap your changes in a simple function, then call it when the page initially loads and whenever the user resizes their browser:

$(document).ready(function() {

  function doSomething() { // Do some stuff // }

Now all we need to do is add a conditional inside our function to check the window width, right? Except this is what has caused so many of us to bang our heads against the wall, because the breakpoints we setup in our CSS don’t actually align with jQuery’s measure of window width - and this measurement can change from browser to browser. And having your JS and CSS disagree on breakpoints is never a good look for your site - unless you're going for a Pablo Picasso style of web design.

So what do we do? One solution is to let someone else do it for you: there are javascript libraries out there (Enquire or Responsive Bootstrap Toolkit, for example) built to solve this exact problem. But perhaps you’re trying to keep your code super lightweight, or only need to do one simple thing and installing an entire library seems like overkill. In this case, we actually can rely on our CSS to provide us with appropriate conditionals: just instead of using the width that triggers the breakpoint, we simply need to check for a result of that breakpoint being triggered.

Let’s say we have a menu icon that’s only visible on mobile, and we need to manipulate the menu markup a little for mobile users. We can use that icon’s visibility to form our conditional:

function doSomething() {
  if ($(“.icon”).is(“:visible”)) {
    // Do some stuff
  } else {
    // Do some other stuff

Now, even though our javascript doesn’t care at all about the screen width, it’s perfectly aligned with our CSS breakpoints. Obviously this won’t work in all situations (I’d avoid checking against an unrelated element, for example, as its styles aren’t tied to what you’re altering and could change independently), but it can offer a quick workaround for many of those headdesk situations we’d like to avoid! And best of all, we did it in a single line of code and didn't need to add additional dependencies to our project.

Have you run into frustrations with viewport-dependent jQuery before? Have solutions of your own? Let us know in the comments!