2

I have some simple JavaScript (embedded in an event) that I want to fire only for small devices. Phones, etc...

Currently I'm doing

if ($(window).width() < 606) {
  do_things();
}

But this feels clunky. Is there a way to only execute this for devices smaller than a certain breakpoint (aside from just setting an earlier variable)? Ideally something that works with my CSS breakpoints.

I'm using Bootstrap, so there may be an easy option that utilizes that.

pppp
  • 231
  • 1
  • 11
AlexQueue
  • 6,353
  • 5
  • 35
  • 44

1 Answers1

6

As crude as your code might look to you, this is actually in a nutshell what a media query is. If you look at the source for responsive.js (JS lib that adds media query support to older browsers) it includes this function:

function getDeviceWidth() {
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        return window.innerWidth;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        return document.documentElement.clientWidth;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        return document.body.clientWidth;
    }
    return 0;
}

While this is a more complete approach to detecting device width (and this is combined with an onResize event handler to detect things like rotation), it is fundamentally what you are doing.

Jason Sperske
  • 29,816
  • 8
  • 73
  • 124