Wednesday, April 07, 2010

Targeting iPad/iPod/iPhone in JavaScript and CSS

Now that the iPad is out, web developers can expect a lot more hits from mobile Safari, which does not behave exactly like its desktop version.

A real-world example of needing to distinguish mobile Safari is the excellent simpleCombo jQuery plugin that allows you to dynamically type a new OPTION element in a SELECT list. Because mobile Safari's keyboard is only available during places where text entry is expected, you can't make this plugin useful in it. However, the plugin still runs and creates an undesired blank OPTION element, so we need to make instantiating the plugin dependent on the browser not being mobile Safari.

As we all know, browser sniffing is a no-no for many reasons, not the least of which is it's not guaranteed forward-compatible. Object detection is the preferred method, and a method common to all three of Apple's mobile platforms is createTouch, the superclass for creating touch events. a method common to both Apple mobile and Android mobile is window.ontouchstart.
if (!(window.ontouchstart===null)) {$("#Department").simpleCombo();}
It's as simple as that.

Now, you ask, what about style sheets? When the platform was iPhone/iPod Touch, you could easily specify a separate style sheet with the MEDIA selector:
<link media="only screen and (max-device-width: 480px)" href="/css/iphone.css">
@media screen and (max-device-width: 480px) {...}
Of course, most of that separate style sheet need had to do with screen space, but there are other considerations as well. So, how do we select both the iPhone/iPod and iPad in one MEDIA selector?
@media screen and (max-device-width: 480px),(max-device-width: 1024px)
That's all there is to it. To exclude this selector (e.g. you want to create a style sheet which contains both normal and mobile Safari styles), just prepend 'not' to 'screen'.