Home > Mobile >  how to display none based on if else
how to display none based on if else

Time:07-14

i want the <p id="demo">kato</p> be displayed none if the user use one of these devices /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript if .. else</h2>

<p>A time-based greeting:</p>

<p id="demo">kato</p>
<p id="sdemo">katod</p>


<script>



if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
                document.getElementById('demo').style.display='none'
                 }
                 
                 else {
                  document.getElementById('sdemo').style.display='flex'
  }


</script>

</body>
</html>

CodePudding user response:

Here is a function that returns the type of device, the user is currently on:

const deviceType = () => {
    const ua = navigator.userAgent;
    if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
        return "tablet";
    }
    else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
        return "mobile";
    }
    return "desktop";
};

Note that the above solution is not always reliable. The value of the userAgent can be easily changed. For example, when we use bots to scrape a website, we can pass a completely different user agent value to hide our identity. It will make it difficult to detect the actual device type.

Then, your code should be as follows and it should works as expected

<!DOCTYPE html>
<html>
   <body onl oad="renderForDevices();>
      <h2>JavaScript if .. else</h2>
      <p>A time-based greeting:</p>
      <p id="demo">kato</p>
      <p id="sdemo">katod</p>
      <script language="javascript">
         function renderForDevices() 
         {
           if( isMobile) {
                       document.getElementById('demo').style.display='none'
                        }
                        
                        else {
                         document.getElementById('sdemo').style.display='flex'
            }
         
         }
         
         const isMobile = () => {
            const ua = navigator.userAgent;
            if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
                return true;
            }
            else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
                return true;
            }
            return false;
         };
         
      </script>
   </body>
</html>

CodePudding user response:

well that's a very complicated question i never seen regex.compile before, but you can still use null.json cause the file is complied already

  • Related