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();
6
  • You should look into using 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. Commented Jun 26, 2014 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. Commented Jun 26, 2014 at 17:58
  • I hope you have code for resize Commented Jun 26, 2014 at 17:58
  • @Huangism ... speaking of things handled automatically by media queries. :-) Commented Jun 26, 2014 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.... Commented Jun 26, 2014 at 17:59

1 Answer 1

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";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.