vendredi 21 février 2020

How to detect the user's browser in javascript & load the class names accordingly?

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';
}



Aucun commentaire:

Enregistrer un commentaire