Mobile Browser Detection Hack

As was surely inevitable, I am now obliged to think more about the experience a user might have of a site while using mobile devices. I could have staved this off for a little while yet longer, but iOS and Android fire the mouseover event in jQuery. Why? Where's the mouse? This gets in the way with a new, mobile-friendly, dhtml menu system I'm creating - works through clicks as well as mouseovers.

Anyway, I thought to either investigate the event handling issue (maybe a jQuery issue) or go for browser detection. As there are more and more mobile initiatives rolling down the pipe for me, detection seemed like it might be more helpful. And, really, I didn't want to reinvent the wheel so I went looking for pre-existing solutions.

I found Detect Mobile Browser, an open-source tool, but it didn't think that iPad was a mobile device. In my framework speed dating session, I said goodbye quickly to the prospect of a long term relationship. I did notice, though, from the USER_AGENT that it was reporting, that all the mobile devices I was checking identified themselves as "mobile" somewhere in the string.

So, a quick hack that seems to do the trick emerged:

First, I convert the javascript file into a ColdFusion file (this ought to be applicable to other frameworks) so that "myfile.js" becomes "myfile.js.cfm". Update the include reference to the point to the updated name and now it is time for the magic of a new session variable:

<cfset session.ISMOBILE = false />
<cfif findnocase("mobile",cgi.HTTP_USER_AGENT) >
<cfset session.ISMOBILE = true />
</cfif>

Detecting the "mobile" substring is crazy easy with results that seem good enough for the application (no idea how feature phone browsers might react, but the whole site is going to be lost on them anyway). Now, anywhere in my code, I can reference session.ISMOBILE to find out if the browser is on a mobile device. So, my script goes from:

$("target").mouseover(function(){
myFunction();
});

To the more mobile friendly:

$("target").mouseover(function(){
<cfif not session.ISMOBILE>myFunction();</cfif>
});

This allows me to mask the phantom mouseover events from iOS and Android devices. That said, I have not had a chance to experiment yet with how other browsers, like Opera, might behave. Anyway, once I blog about the menu, it should be apparent why this is necessary.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.9.1.001. Contact Blog Owner