0

I have the following piece of code. There are 3 desktop sections with class name "desktop-slider" & 3 mobile sections with class name "mobile-slider". Now on every page load, the desktop users should see 1 random section out of 3 from "desktop-slider" & mobile users should see 1 random section from "mobile-slider" on every page load.

Now the below code is working fine for desktops, but even the mobile version is also getting loaded for desktop users.

Now I want to add a condition to detect the users browser or user-agent & accordingly load the respective sections.

Hope I clearly explained the issue. Please help. I am stuck..

window.onload=function() {
      // For Desktops
      var D = document.getElementsByClassName("desktop-slider");
      var m = D.length;
      var n = parseInt(Math.random()*m);

     // For Mobiles
      var M = document.getElementByClassName("mobile-slider");
      var p = M.length; // Mobile
      var q = parseInt(Math.random()*p); // Mobile

      for (var i=m-1;i>=0;i--) {
          var e = D[i];
          e.style.display='none';
      }
    E[n].style.display='block';
}
Sawan
  • 1
  • 2

1 Answers1

0

You can get the user agent like this https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/userAgent or, I suggest you to use a library like this one: https://github.com/faisalman/ua-parser-js

Example:

if (window.navigator.userAgent.match(/Mobile/)) {
 //do something
} else {
 //do something else
}

  • I see. Thanks. But can you please rewrite the above code using NavigatorID.userAgent? – Sawan Feb 21 '20 at 10:59
  • I updated with an example detecting mobile browsers, I don't understand exactly what you wanna do, but with that you have both options you asked for – L. Castillo Barranco Feb 21 '20 at 11:06
  • Now there are 3 sections with the class name 'desktop-slider' & 3 sections with the class name 'mobile-slider'. Users coming from desktops should only see 1 random slide from ''desktop-slider' & no slides from the 'mobile-slider' Similarly Mobile users should see 1 random slide from 'mobile-slider' & no slides from the 'desktop-slider' How to do that using NavigatorID.userAgent ? – Sawan Feb 21 '20 at 11:54
  • Please check the code above & suggest a working code. – Sawan Feb 21 '20 at 11:55