Change style depending on browser userAgent

I feel like I'm really close to this being correct, but it doesn't seem to be working. Could someone please help me?

var userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf('OPR') != -1) {
  if (userAgent.indexOf('Chrome') > -1) {
    //browser is chrome
    $("#evs").addClass(".chrome");
  } else {
    //browser is opera, add css
    $("#evs").addClass(".opera");
  }
}

Upvotes: 1

Views: 297

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206209

  • First you use .toLowercase() but you're trying to match uppercase chars: 'OPR' , 'Chrome'
  • jQuery's .addClass() expects a className string (without the dot) like: $("#evs").addClass("chrome"); - same goes for JS's classList.add() method:

Here's my suggestion:

const UA = navigator.userAgent;
const EL_evs = document.querySelector("#evs");

if (/Chrome\//i.test(UA)) {       // Case insensitive (i) if needed?

  if (/OPR\//.test(UA)) {         // Case sensitive
    EL_evs.classList.add("UA-opera");
  } else if (/Edg\//.test(UA)) {  // Case sensitive
    EL_evs.classList.add("UA-edge");
  } else {
    EL_evs.classList.add("UA-chrome");
  }

}
.UA-chrome { background: gold; }
.UA-edge   { background: blue; }
.UA-opera  { background: red; }
<div id="evs">TEST</div>

Upvotes: 1

Related Questions