1

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

nicael
  • 16,503
  • 12
  • 50
  • 80
r23712
  • 369
  • 1
  • 4
  • 14

3 Answers3

1

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.

  1. 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?

  2. 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.

Community
  • 1
  • 1
Lux
  • 16,183
  • 3
  • 36
  • 64
0

2 solutions:

Community
  • 1
  • 1
Luca Filosofi
  • 30,086
  • 8
  • 65
  • 74
0

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>
Joffrey Maheo
  • 2,889
  • 2
  • 17
  • 23