Handling JavaScript responsively

It’s a very common thing to use JavaScript in our web pages to add interactivity, but in the age of responsive design, we don’t always want that functionality to kick in unless the viewport is the appropriate size.

The problem

You have something triggered by JavaScript on the site you’re building but you want to handle that functionality differently when the viewport is less than 640px.

The solution

What we need to do is:

  • Find the width of the viewport
  • Check to see if the current width is greater than our target width, and if so, execute our code
  • Add a listener to run the above check when the viewport is resized
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Function to check the width of the viewport
var checkWidth = function() {

  var viewportWidth = $(window).width();

  // If the viewport width is greater than 640px
  if (viewportWidth > 640 ) {
    // Execute your code
  } else {
    // Do something else
  }
}

$(document).ready(function() {

  // Call the checkWidth function on page load
  checkWidth();

  // Call the checkWidth function again when the viewport is resized
  $(window).resize(function () {
    checkWidth();
  });
});

How do you handle JavaScript responsively?

This is how I’ve been handling my JavaScript recently and have found that it works really well, however I am interested to hear how others have tackled this same problem.