Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is the best way to detect a mobile device?

Is there an approach to identify whether a user is utilizing a mobile phone in jQuery? Something like the CSS @media attribute? I might want to run an alternate script if the browser is on a handheld device.

The jQuery $.browser function is not what I am looking for.
by

2 Answers

aashaykumar

function isMobile() { return ('ontouchstart' in document.documentElement); }

However above code doesn't take into account the case for laptops with touchscreen. Thus, I provide this second version,

function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
RoliMishra
A simple and effective one-liner:

function isMobile() { return ('ontouchstart' in document.documentElement); }


However, above code doesn't take into account the case for laptops with touchscreen.

function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}

Login / Signup to Answer the Question.