A JavaScript solution for device detection – OS, orientation, and type
As more and more visitors are moving to smartphones/mobiles for visiting websites, it has become important to adjust your website according to the device of the visitors.
For instance, the way your desktop version of the website is presenting the information and different components, it should be presented on smartphones or tablets properly, as well.
For that, you may need to change the CSS or other settings in order to make sure the website adjusts in the viewport and a horizontal scrollbar does not appear. The HTML table width, columns, etc should be adjusted, and so on.
One such solution is using a responsive framework like Bootstrap that adjusts automatically with respect to the user’s device by using its powerful grid system.
The other solution can be detecting the user’s device, operating system, and screen orientation and presenting the website based on that basis.
It also detects the orientation i.e. portrait or landscape.
The plug-in can also detect the operating system of the device including Windows, android, iOS, television, etc.
A demo of using the device.js plug-in
As you open the demo page in any device, it will highlight your device type and orientation. Have a look by clicking the link or image below:
See online demo and code
As I ran this code on the desktop device for this demo, so it displayed the desktop with landscape orientation.
A demo of running device detection plug-in in a smart phone
This time, I executed this code in a smartphone with Android OS. The orientation is portrait. See the graphic below to get the idea or run the demo on a smartphone or tablet:
How to use this device.js plug-in?
- You may download the plug-in from the link given below:
- Credit: matthewhudson
- Direct download: zip file (from Github website)
- After downloading, extract the file and get the device.js file from the lib folder. Place it in the desired location and refer it on the web page before the </body> closing tag.
- A little JavaScript code is also required that you may get from the demo page’s code section.
- You may program to use different CSS and JavaScript for different devices, operating systems, and orientations. You have to go through the device.js file in order to accomplish it.
- Basically, the device.js inserts the classes according to the device in the <html> tag. For complete details, go to the developer’s page by using the above link.