How To Detect Mobile Device Using JavaScript

Many Times , As A Web Developer , We Think That This Specific Element Of Page (Like Modal Box etc.) Should Not Be Visible On Mobile Device. Isn't This ? Right. So For That We Use If Else Condition To Detect Mobile Device & If Detected Device Is Not Mobile , Then Only We Show The Element On The Page.

How To Detect Mobile Device In JavaScript

There Is A Simple Way In JavaScript , By Which We Can Detect That The Device Which Is In Use To Explore Our Page Is A Mobile Or Not. Firstly We Detect The UserAgent & Though Its Result We Can Determine The Device.

JavaScript Code To Detect Mobile Device

    function detectdevice() {
      if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        //detected device is mobile
        alert("Mobile Device Detected");
      } else {
        //detected device is no mobile
        alert("This Is Not A Mobile Device");
In The Above Code, We Have Created A Function With Name 'detectdevice()' [You Can Change The Name According To Your Choice]. Call This Function Whenever You Need To Detect The Mobile Device.

Code Output

As You Can See Above , We Got An Alert Stating That , 'This Is Not A Mobile Device'. In This Way , By Following These Steps & Code , You Can Detect Mobile Device Using JavaScript.