Reputation: 17
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
Reputation: 206209
.toLowercase()
but you're trying to match uppercase chars: 'OPR'
, 'Chrome'
$("#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