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

Using PHP, eliminate all hyperlinks from the DOM HTML

I have a string called $processhtml that contains some HTML. My goal is to remove all link tags and their contents from the HTML using PHP. For example: "This is some text with <a href="#">link</a>" should become: "This is some text with" ...

Aligning the image at the center within a flex container

I am struggling with aligning an image and a link inside a div using the display: flex property. This is how my code looks: <div style="display: flex;"> <div class="site-title-container"> <img style="border-radius: 7px; width: 34px; h ...

Choosing descendant elements in CSS styling

Is there a way to select child elements in sequence? For instance: <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li> ...

What steps can I take to address the div issue in my React application?

After implementing Browser Router, I am encountering whitespace on the left and right side of the navbar. How can I resolve this issue? Below is the code snippet: <div className="container my-3"> <BrowserRouter> ...

Modify the URL of the button based on the chosen option

How can I dynamically change the URL of a button based on the selected option? For example, if someone selects "center", the button URL will be changed to "center.html". I have come across some examples that use the value in the option field. I have trie ...

Tips for positioning a text link alongside an image link within a table row using only inline styles

I am struggling to align text and an image link next to each other within a table row. The image keeps moving up and down despite my efforts to use various alignment and display block styles. I am only able to use inline CSS and need it to display correctl ...

Conceal the div based on the criteria

I need an inline solution for this issue: <div id="xy<%=statusCount%>" style="margin-top: 50px;display:${<%= statusCount %>!=0 ? 'none' : ''};" class="XYZ"> This code is causing an error ...

@page Css not displaying properly on the Mozilla Firefox browser

In order to fulfill my requirement, I need to ensure that there is a consistent 10cm margin on all pages when printing. Printing on my web page involves utilizing the window.print() function. However, due to the dynamic nature of the content, the number o ...

Adjust the height of the image using CSS while maintaining its aspect ratio within the Gall-Peters projection

I've implemented a Gall-Peters projection on my website and I'm looking for the right CSS code to maintain its aspect ratio. I want the image to take up 100% of the available width without elongating the countries' shapes. Can anyone help wi ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

What is the best method to override the CSS transition effect with JavaScript?

I am trying to implement a CSS transition where I need to reset the width of my box in advance every time my function is called. Simply setting the width of the box to zero makes the element shrink with animation, but I want to reset it without any animati ...

I'm having trouble getting Pycharm to locate my static files

My Pycharm is having trouble locating my CSS files. I've attached a screenshot showing the settings.py file, the directory where the .css file is located, and the error message from the terminal indicating a 404 error. Could someone please help me ide ...

Continuously spinning loading icon appears when submission button is triggered

We are currently experiencing some issues with our mobile forms. Our users utilize a mobile form to submit contact requests, but the problem arises when they hit 'submit' - the loading icon continues to spin even after the form has been successf ...

What is the significance of $() in jQuery?

I understand that $() is a selector, but I find it puzzling as to what it actually selects since there is nothing inside the parentheses. Is this a common practice or frowned upon in coding conventions? An example of where I have seen it used is when maki ...

Is there a way to retrieve the disabled drop-down field value after submitting the form?

I'm struggling with a dropdown field that becomes disabled once an item is selected. After submitting the form, the dropdown field loses its value and I'm left with an empty field. Any suggestions on how to keep a value in the dropdown after subm ...

Alter the color scheme of Fancybox's background

I am looking to create a transparent background color for Fancybox. The typical method involves using ".fancybox-skin" in CSS, however this will affect all fancyboxes and I require it to be unique. Therefore, the setting must be sent with wrapCSS. Fancyb ...

Exploring search capabilities within D3 graph nodes

After creating a JSON file with four tiers and utilizing D3.js's collapsing box format to visualize it (source: https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460), I've run into an issue. The problem stems from the sheer size of the J ...

Updating children of specified parents using jQuery

I have a collection of files in a directory and some file icons need to be changed as the default ones are not specific enough. Due to limitations, I can only achieve this using jQuery to insert the code since the mimetype function cannot be modified. Bel ...

When the collapse button is clicked, I aim to increase the top value by 100. Subsequently, upon a second click, the top value should

https://i.stack.imgur.com/p9owU.jpghttps://i.stack.imgur.com/Kwtnh.jpg I attempted to utilize jQuery toggle, but unfortunately, it is not functioning as expected. <script> $(document).ready(function () { $(".sidebar ul li&quo ...

Storing the value of the current vertical scroll position in a variable using jQuery

I'm currently dealing with a challenge that involves using the value of (window).scrollTop() as a crucial variable in my project. What I aim to accomplish is to retrieve and utilize the specific scroll value at a particular moment within an if stateme ...