Alter the CSS display based on the user's userAgent if they are using an iPhone and window.navigator.standalone is set to true

Looking to create a unique webAPP with different content displays based on how it is accessed.

  1. If the user opens the webAPP through their Safari browser
  2. Or if they open the webAPP from a webclip on their home screen

The detection is functioning, as confirmed by document.write, but the CSS display property refuses to change. What could be causing this issue?

Appreciate any help in advance!

<html>
<head>
<meta name="apple-mobile-web-app-capable" content="yes">
<script type="text/javascript">
if (window.navigator.userAgent.indexOf('iPhone') != -1) {
    if (window.navigator.standalone == true) {
        // document.write('<p>homescreen<\/p>');
        document.getElementById("homescreen").style.display = 'block';
    }else{
        // document.write('<p>safari<\/p>');
        document.getElementById("safari").style.display = 'block';
    }
}else{
        // document.write('<p>no iOS<\/p>');
        document.getElementById("ios").style.display = 'block';
}
</script>
</head>
<body>

<div id="homescreen" style="display:none;">
you opened it from the homescreen
</div>

<div id="safari" style="display:none;">
you opened it from safari
</div>


<div id="ios" style="display:none;">
you have no iOS
</div>



</body>
</html>

Answer №1

The <script> tag is executed before the DOM content is fully loaded, causing document.getElementById("xx") to return undefined. Check your browser's JavaScript error console for a message like: "Uncaught TypeError: Cannot read property 'style' of null".

  1. Consider moving the <script> block to the bottom of your HTML body
  2. Alternatively, you can leverage jQuery and utilize something like the following example:

    $(function() {
      if (window.navigator.userAgent.indexOf('iPhone') != -1) {
        if (window.navigator.standalone) {
          $('#homescreen').show();          
        }else{
          $('#safari').show();
        }
      }else{
        $("#ios").show();
      }
    });
    

An even better solution could be to dynamically assign classes to the <body> element, allowing for easy manipulation through CSS.

$(function() {
   if (window.navigator.standalone) {
     $('body').addClass('standalone');
   }
});

This way, different sections of the content can be easily shown or hidden based on these defined identifiers in CSS.

.someContent { display: none; }
body.standalone .someContent { display: block; }

For targeting mobile devices like iPhones, it may be preferable to use CSS media queries such as

@media only screen and (max-device-width: 480px)
instead of relying solely on JavaScript user agent checks (note that the existing indexOf implementation won't cover iPads or iPod Touches).

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

The functionality of a pop-up window is not compatible with Google Maps

I recently implemented a script on my webpage that triggers a popup window every time the page is loaded. Here's how the script looks: <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>ColorBox de ...

Increase the size of the class element when hovered over

I have assigned a class to the "next" and "previous" functions on my webpage, and I am interested in increasing their size on hover so that they take up more space and push the other elements aside. For example: When I hover over the NEXT button, I want i ...

Achieving both vertical and horizontal center alignment specifically for mobile devices

Is there a way to center a column on mobile devices only while maintaining a fixed height for the section? <div class="" style="background-image: url(image url;); background-position: right bottom; background-size: cover; height: 462px;"> <div cl ...

"Create dynamic tables with AngularJS using ng-repeat for column-specific rendering

I have a model called Item with the following structure: {data: String, schedule: DateTime, category: String} I want to create a report that displays the data in a table format like this: <table> <tr> <th>Time Range</th&g ...

Prevent selection on all elements except for input fields with the type of text

I am facing a challenge where I need to prevent selection on a website page for everything except input[type=text] elements. The answer provided in this accepted response to a similar query almost solves the issue. However, it doesn't stop users from ...

Ways to access nested div children without using identifiers

To customize the width of a specific div using jQuery, I need to target the following structure in my HTML code. Although parts of it are generated by a lightbox plugin, the part that sets it apart is the unique class "xxxgallery": <div class="xxxgalle ...

Is there a way to dynamically shift arrow key focus onto buttons in Angular using the left and right arrow keys?

I am facing an issue where pressing the arrow keys left and right does not focus or allow me to navigate through these buttons using the arrow keys. However, when checking the keycode values, they are printed according to the key pressed. I would like to k ...

browsing through elements in express-handlebars

this is the data structure I pass to my handlebars template module.exports = function(showHeader, userId){ // defining the model return { userId: userId, seminars: userSeminars; }; }; var userSeminars = [{ // sample data seminarId: 1, ...

Numerous objects come into view as you scroll

I found a code snippet online that animates items as they appear on scroll. However, the code only triggers animation for one item at a time. How can I modify the code to trigger the animation for all items? const observer = new IntersectionObserver(e ...

Is there a way to transfer a value set from one tpl file to another tpl file in cscart using smarty template engine?

I am trying to retrieve the value of a variable set using an input tag from one tpl file. Here is the input tag in A.tpl file: <input type="checkbox" class="checkbox" name="payment_data[processor_params][enable_addbillcard]" id="optional_enable_addbil ...

Using JavaScript to modify the -webkit-animation-play-state

Hello, I'm currently facing a challenge in changing my css3 -webkit-animation-play-state property from paused to running upon clicking on another div. Does anyone have any suggestions on how I can achieve this? I believe JavaScript might be the way to ...

What is the best way to combine items from two separate lists into a single list by simply clicking on the items using JavaScript and PHP?

Having encountered some issues with setting up a list of items and moving them between each other, I was wondering if it is possible to have multiple lists with a link inside each item that allows for moving it to a specified list. For example, having a li ...

Automated vertical alignment of rows within the Bootstrap table

I'm currently working on a table for my personal project that populates with data from the database. I am trying to get the rows to display vertically under headings (see screenshot at the bottom of this question). I have attempted various solutions f ...

Fancybox 2 - CSS styles vanish when using Ajax request

I have a fancybox2 with static dummy content that has styling applied. It works fine, but now I need to load dynamic content via ajax. However, when I make the ajax call, the required content loads but loses all css styling, most likely due to changes in t ...

Ways to enclose this text with a white border and apply a box-shadow

How can I modify text similar to this image and what is the process involved? ...

Can a .String file be utilized similarly to Localizable.String, but with the ability to change the language using a button?

Is it possible to dynamically change the language of a .String file in an application using a button, rather than relying on the device's language settings? If not, is there a way to specify how to use the EN language within the FR language, for examp ...

Tips for effective page management

After creating a navbar in my project, I've come to the realization that it requires a component for each page and subpage. This seems redundant especially when dealing with multiple navigation options like shown in this image. Is it necessary to crea ...

Adjusting the CSS based on the screen's resolution and size

Currently, I am working with a client who needs interfaces to be adapted for two screens with a resolution of 2560x1600. The challenge is that both screens have the same resolution but different screen diagonals. One has a 27" diagonal and the other... on ...

Tips on eliminating the blue color from a hyperlink within a button

Currently, I am in the process of designing an HTML email template. I have included a green button in the template and now need to eliminate the blue color from the hyperlink within the button. I have exhaustively tried different solutions such as using ! ...

Is there a way to automatically transfer the ID from the first table to the id_position field in the second table upon clicking submit?

I'm dealing with two tables and I need to figure out how to add the id of the first table to the position_id field of the second table upon submitting. My request is done through ajax. The fields for the second table are dynamic, meaning you can keep ...