I'm trying to hide a javascript script block from desktop and be able to show it on mobile only.
<script type="text/javascript">
javascript code
</script>
Thanks
I'm trying to hide a javascript script block from desktop and be able to show it on mobile only.
<script type="text/javascript">
javascript code
</script>
Thanks
Well, its not 100% clear what you mean, but I assume you want to execute some JS code only when you are on a mobile device!
There have two ways to accomplish this.
You can try to analyze the HTTP request on the server and inspect the User-Agent header to find out if it's a mobile browser. Depending on that you can generate the script block or not. What server side enviroment are you using?
Or you wrap the JS code in an if
, and execute it depending on the User-Agent, which you analyze on the client. Look here for more information on how to do that.
1 - make the check server-side http://detectmobilebrowsers.com/ then serve the js code you want.
2 - make the check client-side http://modernizr.com/ then load the script you want using the yep/nop pattern
You can make this with check User Agent, so if you want hide javascript block from desktop browser you can use PHP, like this :
<?php
if( strstr($_SERVER['HTTP_USER_AGENT'],'Android') ||
strstr($_SERVER['HTTP_USER_AGENT'],'webOS') ||
strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') ||
strstr($_SERVER['HTTP_USER_AGENT'],'iPod')
): ?>
<script type="text/javascript">
javascript code
</script>
<php endif; ?>
Or you can use javascript inside your tag if you want run your code only for mobile device :
<script type="text/javascript">
if( navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPod/i)
){
javascript code
}
</script>