f w h

Simple Mobile Detection for JavaScript

One common question I see asks how one might conditionally run JavaScript based on screen size. There are a number of use cases for this, and there are a couple ways to go about it.
One easy way, as I wrote about almost exactly three years ago is to detect a CSS property based on a media query.
Another possibility is to use JavaScript to pull the size of the browser’s viewport. To make things easy, we can package everything in a neat little function that returns an object with the viewport details.

function viewport(){
  this.w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  this.h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  this.orientation = this.w > this.h ? 'landscape' : 'portrait';

  this.output = {
    w: this.w,
    h: this.h,
    orientation: this.orientation

  return this.output;

The function can then be used in a number of ways.

// Conditionally do a thing inside a function
function doAThing(){
  if(viewport().w < 480){
    // Do a thing

// Do a thing when the browser is resized
window.onresize = function(){
  if(viewport().orientation == 'portrait'){
    // Do a thing

UPDATE July 2017: JS matchMedia API

Recently, SitePoint updated one of their 2011 posts to recommend this API.
In short, matchMedia returns a mediaQueryList object, which has a .matches() method attached to it. Passing a media query formatted the same as a CSS media query will return a boolean based on whether the query matches.
Read more about it on SitePoint’s How to use Media Queries in JavaScript.