in Code

Simple JavaScript function to check whether user is on a mobile device

I needed a piece of code to check whether the user is viewing the website from a mobile device like an iPhone or Android phone. So here is a function that I made that’ll help you if you need the same. This code is not the best to be used to make design changes according to the screen size. I suggest people use CSS media queries for that.

A useful situation could be if you have something on your webpage that mobile browsers must handle differently. Maybe a download button that downloads different formats of video for various devices. Or whatever.

Here is the code:

var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (isMobile) {
//It's a Mobile device
} else {
//Not a mobile
}

Hope some of you find this useful. I’m planning to make more code snippet posts.

Write a Comment

Comment