Responsive Design Media and Custom JS

JavaScript logoSometimes, when coding in JavaScript, we risk being too “PHP-centric,” forgetting the beauty of JavaScript’s asynchronous nature. For instance, when developing responsive behavior for a site’s front-end, it is a common practice to write something like this:

But the obvious drawbacks of this approach are:

  1. The threshold value stays hardcoded in a bunch of code snippets so that, if it needs correcting, you need to change code in multiple places;
  2. The inner width might not be the only criterion of a layout mode;
  3. The resize event occurs multiple times so that, while resizing a browser’s window, we need to “debounce” it, which is a performance solution and more of a workaround rather than a feature.

There is a much better, “juicy” JS approach that combines the power of CSS3 media queries to define the layout mode and using custom events instead of conditions to modify layouts.

In order to do this we need:

Once set up with these, we can easily and elegantly implement responsive behavior by taking the following steps:

1. Define the layout modes:

2. The matchMedia objects (e.g. checkDesktop ) have a boolean property  .matches which is true when the media matches the query. We can use it for the initial setup:

3. Moreover, the matchMedia object has a method  addListener() designed to add a listener to the matchMedia object change-state event. (NOTE: The event is executed either when the media enters the matching state or when it disappears.) You have to use the  .matches property of the event to differentiate between these two:

4. In the code above we use the  trigger() method to emit the more high-level “layout” event event, so that listeners like:

catch it, and execute the layout changes.


A FINAL THOUGHT: While writing up this blog piece, I came across a potentially interesting project –  Response JS – which may be able to efficiently replace part of the approach discussed above, requiring less JavaScript to operate on layouts, particularly when loading different sizes of images. It is an experimental jQuery plugin, but might be worth your looking in to!