Reputation: 235
I'd like to build a webAPP and displaying different content, when
The detection works - I check it with document.write - but the CSS display property is not changing. What am I doing wrong?
Thanks upfront!
<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>
Upvotes: 0
Views: 4548
Reputation: 2625
The <script>
is evaluated before the DOM is loaded, thus document.getElementById("xx")
returns undefined
. Check your javascript error console, there's probably an error like: "Uncaught TypeError: Cannot read property 'style' of null".
<script>
block to the end of your bodyBetter yet, use jQuery and something like, see http://api.jquery.com/ready/
$(function() {
if (window.navigator.userAgent.indexOf('iPhone') != -1) {
if (window.navigator.standalone) {
$('#homescreen').show();
}else{
$('#safari').show();
}
}else{
$("#ios").show();
}
});
Or what might be an even better and more flexible alternative is to append classes to the <body>
element, then you can easily show/hide anything using CSS.
$(function() {
if (window.navigator.standalone) {
$('body').addClass('standalone');
}
});
Then in the CSS all sections can easily be shown/hidden based on these identifiers.
.someContent { display: none; }
body.standalone .someContent { display: block; }
For the mobile selector (iPhone), you might even avoid the JS userAgent switch (FYI, your indexOf
wouldn't match iPads or iPod Touches) und better rely on CSS media queries like @media only screen and (max-device-width: 480px)
(this one is for an iPhone landscape & portrait).
Upvotes: 3