0

I want to select a CSS file using a variable from a piece of JS. I'm working on feature detecting to select a specific CSS. Here is the code I'm using to determine the resolution of a screen. I would like to use either "RES" or "device" to select an external CSS. Thanks.

function hasTouch() {
  return Modernizr.touch;
}

var RES = window.screen.availWidth

function detectDevice() {
  if (hasTouch()) {
    if (RES < 600) {
      device = 'phone';
    } else {
      device = 'tablet';
    }
  } 
  if (RES > 600 && RES < 1025) {
    device = 'Medium';
  }
  if (RES > 1025 && RES < 1367) {
    device = 'Large';
  }
  if (RES > 1367) {
    device = 'XL';
  }
  return device;
}

document.querySelector('#device').innerHTML = detectDevice();
Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
user3743202
  • 31
  • 1
  • 3
  • You should look into using [CSS media queries](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries), which can easily select based on width. Touch or not is a bit less standardized right now, but you may be able to find a way. – Dark Falcon Jun 26 '14 at 17:58
  • (a) the resolution-based stuff is *far* better done with CSS Media Queries. They're designed explicitly for this. (b) Detecting devices based on touch is chancy - I have a laptop with a touchscreen, and I'd hate to be presented with a mobile view on that screen. – Paul Roub Jun 26 '14 at 17:58
  • I hope you have code for resize – Huangism Jun 26 '14 at 17:58
  • @Huangism ... speaking of things handled automatically by media queries. :-) – Paul Roub Jun 26 '14 at 17:59
  • CSS media queries, this method is going to make it a pain in the ass considering the types of devices that are out there. iPhone vs Surface.... – VikingBlooded Jun 26 '14 at 17:59
  • Like everyone said, use mediaQueries combined with a :before or :after pseduo-element is much faster and easier, doing it this way will be slow. – Michael Jun 26 '14 at 18:08

1 Answers1

1

Use mediaQueries, you won't even need Javascript.

http://jsfiddle.net/D6hZn/3/

HTML

<div id="device"></div>

CSS

#device:before {
    content: "phone";
}

@media (min-width: 600px) {
    #device:before {
        content: "Medium";
    }

}

@media (min-width: 1025px) {
    #device:before {
        content: "Large";
    }    
}

@media (min-width: 1367px) {
    #device:before {
        content: "XL";
    }    
}

As for touch, I wish you could use mediaQueries for that but it isn't possible (yet). Use Modernizr

CSS

html.touch #device:after {
    content: " touch";
}

html.no-touch #device:after {
    content: " no-touch";
}
Michael
  • 6,895
  • 3
  • 23
  • 19