3

I wonder how to add css and javascript code only when the site is accessed via smartphones.

Currently I'm using media queries, but it does not solve the problems, because currently some smartphones already have higher resolutions than even some tablets and desktops.

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
Miguel Borges
  • 7,549
  • 8
  • 39
  • 57
  • 3
    You really can't tell exactly what sort of device is accessing your site via media queries or anything else except the user agent string. That, of course, is a big mess, because a new Android phone is introduced on an almost daily basis. Why not just make sure your site works well at a wide range of screen geometries? – Pointy Apr 04 '13 at 18:51
  • you can check for mobile browser with php and then allow the CSS and JS to run if the outcome is true. – Kevin Lynch Apr 04 '13 at 18:54
  • 1
    User agents have been misrepresenting themselves since forever and cannot be trusted *ever*. – cimmanon Apr 04 '13 at 18:59

4 Answers4

2

You can use feature detection via. Modernizr to check for touch events.

Alternatively you can use user-agents - check out http://detectmobilebrowsers.com/

The best bet however is to design your website using fluid grid website design so your site adapts well to mobile, tablet and laptop/desktops.

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
  • 1
    What about touchscreen laptops? – Rick Viscomi Apr 04 '13 at 18:51
  • 1
    @cimmanon I know they're not optimal, in fact when it comes to me I haven't used them - I prefer my third method of doing it :) – dsgriffin Apr 04 '13 at 19:01
  • your first soluction don't work, because modernizr check the touch even on computers. the second solution don't distict tablet of the smartphods. the third was ideal, but the layout for smartphones is to be shown on smartphones. and by that logic, if the site was fluid, the Samsung Galaxy 3 was shown the site "normal" and not want it – Miguel Borges Apr 08 '13 at 01:57
  • @MiguelBorges If you want you to do it using separate CSS, then I'm afraid your stuck with Media queries - there are things you can target that will make sure it targets phones only (e.g. Pixel ratio/density) – dsgriffin Apr 08 '13 at 07:39
0

If you are trying to detect high-resolution screens (which doesn't just mean smartphones!), use the device-pixel-ratio media queries: http://css-tricks.com/snippets/css/retina-display-media-query/

What about smartphones are you actually trying to detect?

kevingessner
  • 18,559
  • 5
  • 43
  • 63
-1

If possible, try checking the User-Agent HTTP header on the server side, and dynamically include the necessary css and js files.

Marcos Savoury
  • 317
  • 1
  • 13
-1

You can check the browser's user-agent to see if the user is connecting from a smartphone.

Check out this relevant post

Community
  • 1
  • 1
Zacharious
  • 515
  • 4
  • 13