Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Target ONLY Safari

I'm using this bit of jQuery code to target Safari:

if ($.browser.safari) {
    $('#div1').css({'margin-top': '-22px'});
    $('#div2').css({'margin-top': '-17px'});
}

Oddly, it also targets Chrome (at least Mac version). What jQuery code can I use that would ignore Chrome and target only Safari?

I would be grateful for expert advice.

like image 350
Dimitri Vorontzov Avatar asked Jul 27 '11 18:07

Dimitri Vorontzov


3 Answers

(Edit so that Chrome must not be in the user agent):

(Edit2 because Chrome for iOS has "CriOS" instead of "Chrome" in its user agent):

if (
    navigator.userAgent.indexOf('Safari') != -1 && 
    navigator.userAgent.indexOf('Chrome') == -1 && 
    navigator.userAgent.indexOf('CriOS/') == -1
)  { 
   //i.e. apply safari class via jquery
}

P.S. You should consider using Feature Detection to change your website according to what the current browser can do instead of checking for user agents, which you have to update regulary.

like image 118
Wulf Avatar answered Sep 27 '22 22:09

Wulf


if (navigator.userAgent.indexOf('Safari') && !navigator.userAgent.indexOf('Chrome')) {
    // Yep, it's Safari =)
}else {
    // Nope, it's another browser =(
}
like image 40
cutsoy Avatar answered Sep 28 '22 00:09

cutsoy


Feature detection is preferred over browser sniffing, but I did find this solution on SO:

Detect Safari using jQuery

like image 35
Joe Coder Avatar answered Sep 27 '22 23:09

Joe Coder