Responsive design is everything in web development. I think all entry level developers have a decent understanding of responsive design through using media queries, frameworks like bootstrap, or a combination of the two.

However, what if you need some functionality in your Javascript that you only need on certain devices. You could start changing CSS and getting in a mess to hide/show what you need to, but there is a simpler way. The window.matchMedia  object in JS.




You can use a nice if function using this that will disable certain functionality on different devices. The simplest form example is below:


if (window.matchMedia("(min-width: 400px)").matches) {
  /* the viewport is at least 400 pixels wide */
} else {
  /* the viewport is less than 400 pixels wide */


Choose your device width, add the code that you want to run in the relevant section, and hey presto!

I did this for an overlay I had on my main portfolio site that would appear when clicking on a portfolio item.

Overlay Example

This looked horrible on smaller devices and would not fit properly. I could have changed the sizing using CSS but felt it would be clearer without the overlay for UX.

The code I added worked with a .preventDefault() code snippet which stopped the link going to the portfolio description and instead opens up an overlay.  I simply added a query that only enabled the default prevention code on smaller devices so that they linked directly to the portfolio description page. Awesome!


if (window.matchMedia(“(min-width: 700px)”).matches) {


I got most of the information I needed straight from the Mozilla Development Network, and adapted it to what I needed.

I feel like using this could be useful for so many things, especially if you have a very interactive desktop website and need to switch off some functionality to improve the UX on mobile devices.