Detecting Android devices

Issue: My website functions properly on desktop but has a problem with the carousel images skewing on iPhones. To address this, I created a separate CSS styling for iPhone devices and used a JavaScript function found online to detect iPhones and iPads.

Unfortunately, it seems that the same changes are being applied to Android devices which is not desired. The current JavaScript code used to detect iPhone and iPad devices is as follows:

 <script language=javascript>
            function isApple(userAgent){
              var iPhone = userAgent.match(/iPhone/i) !== null;
              var Apple = userAgent.match(/Apple/i) !== null;
              var Mac = userAgent.match(/Mac/i) !== null;
              var iPod = userAgent.match(/iPod/i) !== null;
              var iOS = userAgent.match(/iOS/i) !== null;
              return iPhone || Apple || Mac || iPod || iOS;
            }
            
            if(isApple(navigator.userAgent)){ 
              document.getElementsByTagName('head')[0].insertAdjacentHTML('beforeend', '<link rel="stylesheet" href="/assets/bootstrap/css/iphone.css">');
            }
        </script>

The CSS styling for iPhones includes specific height adjustments to prevent image skew in carousels:

/* Portrait and Landscape iphone*/
@media only screen 
  and (max-device-width: 480px) 
  and (orientation:portrait) { 
    #homepage .carousel .item { height: 150px !important;}
    #homepage .carousel .item img { max-width: 100%; height: auto; display: block; }

}
@media only screen 
  and (max-device-width: 480px) 
  and (orientation:landscape) { 
    #homepage .carousel .item { height: 250px !important; }
    #homepage .carousel .item img { max-width: 100%; height: auto; display: block; }
}

I have organized my stylesheets in a certain order and suspect this may be causing conflicts:

<link rel="stylesheet" href="#$.siteConfig('themeAssetPath')#/css/theme/theme.min.css">
    <!--- Bootstrap classes overrides --->
    <link rel="stylesheet" href="#$.siteConfig('themeAssetPath')#/assets/bootstrap/css/bootstrap_overrides.css">
    <!--- IPHONE classes overrides --->
    <link rel="stylesheet" href="#$.siteConfig('themeAssetPath')#/assets/bootstrap/css/iphone.css">
    <!--[if IE]>
    <link rel="stylesheet" href="#$.siteConfig('themeAssetPath')#/css/ie/ie.min.css">
    <link rel="stylesheet" href="#$.siteConfig('themeAssetPath')#/css/ie/ie_overrides.css">
    <![endif]-->

    <!--[if lte IE 9]>
        <link rel="icon" href="/images/favicon1.ico" type="image/x-icon" /> 
    <![endif]-->

Is the JavaScript approach for detecting iPhones and iPads correct? Should I create a separate stylesheet for Android devices? If so, a modified version of Javascript for detecting Android devices was found:

$(function isAndroid(userAgent) { // Wait for page to finish loading.
    if(navigator != undefined && navigator.userAgent != undefined) {
        user_agent = navigator.userAgent.toLowerCase();
        if(isAndroid(user_agent.indexOf('android')) > -1) { // Is Android.
            document.getElementsByTagName('head')[0].insertAdjacentHTML('beforeend', '<link rel="stylesheet" href="/assets/bootstrap/css/android.css">');
        }
    }
});  

Any guidance on modifying these approaches would be highly appreciated.

Thank You

Answer №1

Here is a code snippet you can experiment with.

function checkDeviceOS() {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;

  if( userAgent.match( /iPad/i ) || userAgent.match( /iPhone/i ) || userAgent.match( /iPod/i ) )
  {
    return 'iOS';
  }
  else if( userAgent.match( /Android/i ) )
  {
    return 'Android';
  }
  else
  {
    return 'Unknown';
  }
}

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

Looping through a JSON array

Currently, I am working with asp.net in Visual Studio and using jQuery to call a web method. In asp.net, I am generating a dynamic datatable and then returning it by using JsonConvert.SerializeObject(dt). $.ajax({ type: 'POST', url: &apo ...

Strategies to avoid red squiggle lines in a contenteditable div that has lost focus

While the div is focused, spell checking is enabled which works well. However, once the focus is removed and there are spelling mistakes, the red squiggle lines for spell checking remain visible. After following the advice provided in this query: spellch ...

What could be the reason for my select list not showing up?

Hello fellow developers, I am currently working on creating a dynamic tablerow that allows users to fill in input fields and select options from a list for each cell. While the input fields are functioning properly, I am facing an issue with displaying th ...

Authenticating the identity of the client application - the client is currently within the browser

I have a PHP backend (although it's not really important) and a Javascript client that runs in the browser. Here is how the application operates: The user accesses a URL and receives raw templates for rendering data An Ajax GET query is sent to the ...

Find the difference between the sum of diagonals in a 2D matrix using JavaScript

I'm currently practicing on hackerrank and came across a challenge involving a two-dimensional matrix. Unfortunately, I encountered an error in my code implementation. 11 2 4 4 5 6 10 8 -12 The task at hand is to calculate the sum along the primary ...

Using mousedown, mousemove, and mouseup to handle touch events in vanilla JavaScript instead of jQuery

Can someone guide me on how to set up a touch event handler in JavaScript using the mousedown, mousemove, and mouseup events? I would really appreciate any suggestions or tips! ...

The argument type does not match the parameter type partial<>

While attempting to validate my Ionic React form, I encountered an error when calling the validationSchema within the useForm method. The specific error message received is as follows: Argument of type '{ validationSchema: ......' is not assignab ...

Hover over the first element to remove its class and replace it with a different element

I am attempting to develop a function that adds the class = "actived" to the first Element. This class has a CSS style that highlights the element in question. I have a list of 4 lines and I want the first one to automatically receive this class, while t ...

Dynamically parallelizing functions with async and arrays

I have recently integrated the fantastic "async" module by caolan into my Node.js project: Below is a snippet of the code in question: exports.manageComments = function(req, res) { var toDeleteIds = []; var deleteFunctions = []; if (req.body. ...

Positioning a div to the right of another div within a container (box)

I'm currently trying to line up two divs alongside each other within a box. Using angularJS, I am dynamically generating input boxes and looking to include an image for the delete option next to each input box. Despite using "display: inline-block", I ...

Output JSON data to an HTML5 table

Here is a code snippet to retrieve data: function fetchInformation(){ $.get('http://mywebsite.net/getFile.php', function(data) { var result = JSON.parse(data); } The returned JSON data is as follows: Object {0: "11", 1: ...

Leveraging Material-UI in Electron Environment

I'm currently working on an electron app using React and incorporating Material-UI for the user interface. I've added a datepicker and timepicker to a component, but when clicking on the input in the electron app, nothing happens. I'm unsure ...

Having trouble with your angular.jg ng controller functioning properly?

Having trouble getting any content to show up from the media object! The plate object seems to be malfunctioning. <!DOCTYPE html> <html lang="en" ng-app="confusionApp"> <head> <meta charset="utf-8"> <met ...

Inquire about understanding Mean.js through form submission

Hey there, I'm looking to create a search engine for an application using JS MEAN. I have a database with various elements and I want users to fill out a form to see the results in a separate view. I haven't had much luck so far, I've don ...

The div element is not extending all the way to the left side of the browser window

I'm having trouble positioning a menu at the top of my webpage following a tutorial. The menu icon doesn't seem to reach all the way to the left side of the page. Despite multiple attempts to adjust the margin and padding settings, I can't ...

Using AngularJS Material's mdDialog to show locally stored data in a template

In the controller, the section responsible for spawning mdDialog appears as follows: $scope.removeAttendee = function(item) { console.log(item); $mdDialog.show({ controller: DialogController, templateUrl: 'views/removeMsg.tm ...

What are some methods to secure my API keys within my React application?

What steps can I take to secure my api keys in my react application? Should I incorporate something with express? My goal is to avoid creating any server-side components to handle the API calls. Currently, my backend is managed by firebase but I also uti ...

Refresh the Dom following an Ajax request (issue with .on input not functioning)

I have multiple text inputs that are generated dynamically via a MySQL query. On the bottom of my page, I have some Javascript code that needed to be triggered using window.load instead of document.ready because the latter was not functioning properly. & ...

Change the class of an element only within the div that is directly below it

Trying to achieve: Visit this link In my navigation menu, I have two folders with subpages under them. The CSS for displaying the page titles within the folder is as follows: .main-nav .subnav ul {display:none; transition: all 100ms ease-in-out; } .mai ...

The Vue-cli webpack development server refuses to overlook certain selected files

I am attempting to exclude all *.html files so that the webpack devserver does not reload when those files change. Here is what my configuration looks like: const path = require('path'); module.exports = { pages: { index: ...