How to Use JavaScript to Detect Devices

The great thing about JavaScript is how it enables you to dynamically make changes to your code based on certain events or conditions. One such condition that might cause you to want to make changes to  your code (or at least some slight modifications) is which type of device is being used to view your projects or web pages. This is because each mobile device (iPhone, Android, iPad, etc) have different dimensions and aspect ratios that unfortunately don't always respond to your code and display your designs in exactly the way you'd like. Luckily, JavaScript provides a very easy and simple way to test for a particular type of device and execute some code based on whether or not your user is using the particular device you've singled out.

Check out the snippet below to see how it works:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
 // Do something
} else {
 // Do something else

Obviously, the snippet as it stands wouldn't really do anything. You ned to choose one of the 7 device options provided and use that with the .test() method to test for that one particular device you're trying to compensate for (if you want to set code specific to another type of device, you'll have to add another if statement). Then, once you've selected the type of device you're trying to write code for, you can insert the code you want to be executed into the if statement. You can be trying to change the color, shape, or dimensions your elements so that they better fit within the viewports of your chosen type of device, or you can simply use the code to troll iPhone users (see example below) -- it's totally up to you.

Check out the example below to see one way in which you can use the device detector code.

if( iPhone.test(navigator.userAgent) ) {
 alert("Androids Rule");
} else {
 alert("Congratulations, you're not using an iPhone");

Responsive Menu
Add more content here...