A guide on identifying browsers and devices with javascript and css

I am looking to determine whether the device is a desktop, mobile, or tablet. Based on this information, I want to switch the image directory accordingly.

if (getDeviceState() == 'phone') {
              alert("phone");
          }
          else if (getDeviceState() == 'tablet') {
              alert("tablet");
          }
          else {
              alert("small-desktop");
          }

I have attempted to achieve this using both CSS and JavaScript.

          var indicator = document.createElement('div');
          indicator.className = 'state-indicator';
          document.body.appendChild(indicator);

          // Create a method to determine device state
          function getDeviceState() {
              var index = parseInt(window.getComputedStyle(indicator).getPropertyValue('z-index'), 10);

              var states = {
                  2: 'small-desktop',
                  3: 'tablet',
                  4: 'phone'
              };

              return states[index] || 'desktop';
          }
          if (getDeviceState() == 'phone') {
              alert("phone");
          }
          else if (getDeviceState() == 'tablet') {
              alert("tablet");
          }
          else {
              alert("small-desktop");
          }

And in the CSS:

/* small desktop */
@media all and (max-width: 1200px) {
    .state-indicator {
        z-index: 2;
    }
}

/* tablet */
@media all and (max-width: 768px) {
    .state-indicator {
        z-index: 3;
    }
}

/* mobile phone */
@media all and (max-width: 360px) {
    .state-indicator {
        z-index: 4;
    }
}

However, I am encountering difficulties distinguishing between landscape and portrait states. Thus, it may be more effective to use user agents rather than relying solely on CSS.

Answer №1

To determine the device type, you can implement device.js. For more information about this library, visit

You can access the source code and examples by visiting the following link: https://github.com/matthewhudson/device.js/tree/master

Below are the methods you can use to identify the device type:

device.mobile()
device.tablet() 

And to determine the orientation of the device, utilize the following functions:

device.landscape()
device.portrait()

Answer №2

In HTML, there is a field called user agent used to transmit device information:

Laptop or Desktop Computer

mozilla/5.0 (windows nt 6.3; wow64) applewebkit/537.36 (khtml, like gecko) chrome/36.0.1985.125 safari/537.36

iPhone Device

Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B176 MicroMessenger/4.3.2

Windows Phone Model

UCWEB/2.0 (Windows; U; wds7.10; zh-CN; Nokia 900) U2/1.0.0 UCBrowser/8.6.0.199 U2/1.0.0 Mobile

  1. Kernel Engine

    IE、Gecko、WebKit、Opera

  2. Browser Type

    IE、Chrome、Firefox、Opera

  3. Operating System

    Windows、Mac、Unix

  4. Mobile Devices

    iPhone、iPod、Android、Nokia

You can perform detection in the following way:

    var ua = navigator.userAgent.toLowerCase();
    //check for specific devices like this
    isChrome = ua.indexOf("chrome") > -1

Answer №3

By utilizing JavaScript, it is possible to retrieve the window's outerHeight and outerWidth properties to determine the device size. Additionally, you can analyze the navigator.userAgent string to identify the user's browser.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain meta title and description using JavaScript

I'm having trouble retrieving the meta title and description from websites entered into the URL field. When I input a URL and click fetch, nothing appears. However, when I hardcode "https://www.espn.com/" in the JS function, it pulls in the entire web ...

Managing JavaScript promise rejections

What is the best approach to managing an error, such as the one labeled "new error" in the code snippet below, that occurs outside of a promise? function testError() { throw new Error("new error") // How can this error be properly handled? var p ...

Issue with Mongoose schema: Unable to access the property 'password' as it is undefined

I recently attempted to implement passport local authentication based on a tutorial I found. Although everything appeared to be working correctly, I encountered an error when making a request using Postman: [nodemon] 1.18.11 [nodemon] to restart at any ti ...

Storing historical data of file uploads on user accounts using PHP

I need a solution to keep track of the files uploaded by users on my website using PHP sessions. My goal is to allow users to see a list of their uploaded files once they log in to the designated page for file uploads. Can this be achieved using only PHP ...

How can I hide the title bar on screens in expo?

As a newcomer to the world of react-native, I rely on YouTube tutorials to assist me in creating projects. Currently, I am working on developing an expo ui-app, however, each screen I create displays a title at the top, such as this example: https://i.ssta ...

How can we dynamically navigate to the next line within the Material UI DataGrid component when space is limited?

Currently, I am working with the datagrid component from material ui. I have retrieved some data from a database and am attempting to pass it to the datagrid component. However, I have noticed that certain fields contain long strings which do not fully app ...

Encountering an error when trying to use variable values for D3 chart instead of static json files, which are working

Our challenge is to retrieve JSON values from a variable (data) and pass them to D3 as JSON input. However, we are encountering an error in Firebug stating "data.links is not defined". The chart displays correctly when we use the JSON values from the sampl ...

Challenges arise when incorporating interfaces within a class structure

I created two interfaces outside of a class and then proceeded to implement them. However, when I tried to assign them to private properties of the class, something went wrong and I'm unable to pinpoint the issue. Can anyone offer assistance with thi ...

Adding a class to a list item depending on the current URL - A step-by-step guide

Currently, my website boasts an impressive navigation bar, but I want to take it up a notch. My query is: Is there anyone who can assist me in refining my JS Script so that, depending on the current URL, the respective list item in my menu will be assigne ...

Troubles with displaying information retrieved using useEffect within a personalized hook

Delving into the world of React and utilizing React hooks as a beginner can be both exciting and challenging. I've come across a scenario where I'm working with a function component that is responsible for displaying information on the page. Whil ...

Pass numerous URL parameters through an ajax get request

Currently, I am working on developing an ajax page for my project. In this page, I need to send an ajax request with multiple URL parameters. These parameters should be retrieved from HTML text boxes. Strangely, when I pass the parameters using code direct ...

What could be the reason for the hr tag's CSS not appearing in React code?

In my React code, I am trying to create a border using the following code: <hr className="borderLine" /> However, when I attempt to style it with CSS, I utilize this snippet of code: .divider { margin: 2rem; width: 100%; color: ...

Error: Unable to access the 'stopPropagation' property of a null object - ReactJS

React Component export default class CommentBox extends React.Component { constructor() { super() this.state ={ showComments: false, comments: [ { id: uuid.v4(), author: 'Clu', body: 'Just say no to love!&apos ...

What is the optimal location for storing numerous blocks of text (without utilizing a database)?

If I have a control used on 10 different pages with a help icon, each page needs to display its own unique paragraph of help text. The selection of which help text to show is determined by a JavaScript function. In my scenario, having 10 paragraphs will n ...

Unable to upload files using Jquery.form (3.51.0-2014.06.20) in IE9 within a Sharepoint application

Before diving into this issue, I want to clarify that I have thoroughly researched similar problems on Stack Overflow and other forums related to jQuery form upload problems. However, I am confident that the issue I am experiencing is unique. The problem ...

Efficient AJAX validation using PHP and JavaScript

I am currently working on a small website project that requires User registration functionality. One key aspect is ensuring that the system prevents users from registering with usernames that are already in use. Most modern websites employ AJAX to verify ...

Attempting to understand the concept of "this" in my JavaScript code. One aspect is functioning correctly while the other is not

Currently, I am improving my knowledge of JavaScript by reworking certain jQuery examples from a reference book. In this particular snippet of code, I am implementing a click listener for a tab to change to an active state once the user clicks on it. va ...

Do Typescript code require the use of a constructor?

After initializing a fresh Aurelia project using the aurelia-cli and executing the au new command, I received the following app.ts: export class App { message = 'Hello World!'; } To enhance my app.ts, I replaced it with the code from a helpfu ...

How to Submit a Form Using Jquery

Is it possible to submit a form using JQuery without the need for page reload? A Sample Form: <html> <form method="post" action="submit.php"> <input type="text" name="name"/> <input type="submit" name="submit" value="submit"/ ...

A guide on updating the color of a Button component (Material UI) when dynamically disabling it

In a React table, I have a button that is disabled based on the value in an adjacent column. For example, if the value in the adjacent column is "Claimed", the button is disabled. However, if the value is "Failed" or blank, the button can be clicked. Curre ...