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

issues retrieving data from firebase firestore with flutter's orderBy()

I've been working on developing a group chat app using Dart-Flutter in Android Studio. Everything was going smoothly until I encountered an issue with displaying messages in chronological order based on the time they were sent. To address this, I adde ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

What did I overlook in my AJAX implementation?

When a user selects a value from the dropdown menu, an Ajax call must be made to the server to retrieve some values in JSON format. Below is the Ajax code //AJAX Security $('#ddlSecurityLevel').change(function () { if ($('#ddlSecurityL ...

Create Stylish Popups and Spacious Containers with CSS

A unique pure css popup was crafted by merging and . Hovering over "John Smith" triggers the appearance of the popup. The code for this can be seen at http://codepen.io/kikibres/pen/MwEgQX. However, there are some challenges being faced. The aim is to ke ...

PhongMaterial designed specifically for rendering InstancedBufferGeometry

I am working on creating a scene with thousands of simple meshes, and I decided to implement InstancedBufferGeometry for better performance. Most of my code is based on the example provided here: Although instancing works well, it seems to only function p ...

Showcasing a contact from the address book - Developing for iPhone

I have an iPhone app using the AdressBookUI framework and I need help displaying a person. I already have their ABRecordRef, but I'm not sure how to go about displaying them. All I really want to show is their name, picture, and phone numbers. Can so ...

Struggling to troubleshoot an error - Invalid key Token '{' found at column 2

I am encountering a debugging issue that I can't seem to resolve. form-field.html <div class='row form-group' ng-form="{{field}}" ng-class="{ 'has-error': {{field}}.$dirty && {{field}}.$invalid }"> <label cla ...

Include the aria-labelledby attribute in the jQuery Datatable Pagination

Check out the HTML output created by the Jquery Datatable plug-in for pagination(https://datatables.net/plug-ins/pagination/full_numbers_no_ellipses): <div class="dataTables_paginate paging_full_numbers" id="my-table_paginate" aria-l ...

How can I use JavaScript api calls to retrieve an image url and insert it into an image tag in an

I have a JSON object that I need to use to retrieve images from a remote URL and display them in the img tag using API calls. The API link can be found at <div class="emoji"> <ul id="emojiz"></ul> <span style= ...

Dynamically populating checkboxes and dynamically setting their checked state

I'm working with a for loop that dynamically generates 7 checkboxes in a row. Here's how it looks: @for (int i = 1; k < order.Rows.length; i++) { Row: @i <ul> @for (int j = 1; j < order.NumCheckboxes.length; j++) ...

What is the best way to implement spacing between the navigation bar logo, search bar, and links using flex in Bootstrap 5?

I want to customize the layout of my navigation bar using Bootstrap 5. Specifically, I would like the logo text to be on the left, the search bar in the middle, and the user links on the right. How can I achieve this using Bootstrap 5? <!-- NAVIGATION ...

Is it possible for the relative path of a gif image to become invalid when added to a div?

Question Context: In the view, I have a form that will show a loading 'spinner' gif when a user submits it. The Problem: If I place the spinner img element within its container div, the spinner is always displayed, which is not desired: https ...

Error Alert: Next.js TypeScript is reporting that the necessary packages are missing from your setup

As I work on developing a basic Next.js website using their TypeScript starter, everything was going smoothly with the 'yarn dev' command. However, out of nowhere, I started encountering an error message whenever I tried to run 'yarn dev&apo ...

Transferring an object from the factory to the controller

I'm currently working on setting up a factory that sends an ajax request to an API and then returns a data object. Here is the code snippet I have written: app.factory('Test', function($http, $q) { var data = {response:{}}; var getM ...

JavaScript enables users to store over 5 megabytes of data on their client devices

Is there a way to store more than 5mb in the client browser? I need this functionality across various browsers including Firefox, Chrome, Internet Explorer, Safari (iOS), and Windows Phone 8 Browser. Initially, localStorage seemed like a viable option as i ...

Make sure to stay updated with any new notifications through Firebase Cloud Messaging (FCM)

I am currently exploring ways to detect changes while connected to Firebase Cloud Messaging. Notifications are being sent to my Android project on Firebase, prompting me to regularly check for new notifications within the Android application. Is it necess ...

abandoning the upload of an item into a THREE.js environment

Currently, I am working on a THREE.js scene where I need to prevent uploading multiple files into the scene simultaneously. The setup involves using Angular to implement the three js scene and canvas as a factory to maintain only one instance of a canvas a ...

Error: Unexpected data type encountered. Expected an array but found a string instead at line 1, column 2

I have tried multiple suggestions from similar questions but none of them have helped. How can I successfully execute this test? @Test fun isJsonCorrectPersonConvert() { val gson = GsonBuilder().create() val json = gson.toJson("[{\"Id\": ...

JavaScript Countdown Timer Programming

I've scoured countless resources, but most of them only provide code for counting down to a specific day. I'm reaching out in the hopes that someone can assist me by crafting some JavaScript for the following HTML structure. This section of my w ...

What is the best way to restrict event handling to only occur once every X seconds using jQuery or JavaScript?

Is there a way to limit handling the event of a rapidly-firing keypress to once per X seconds using jQuery or vanilla JavaScript? Check out this jsfiddle that demonstrates rapid keypress firing without any limiting on the handling: View here ...