0

If I use Chrome I want to show img1.jpg (<img src="img1.jpg" alt="my Chrome Image">). Otherwise, if I use IE, I want to show img2.jpg (<img src="img2.jpg" alt="my IE Image">). Is it possible?

Thanks in advance.

eightShirt
  • 1,387
  • 2
  • 13
  • 25
  • 1
    Yes it is. http://jsfiddle.net/1s22amge/ – blex Mar 15 '15 at 22:00
  • possible duplicate of [Check what kind of browser the user is using](http://stackoverflow.com/questions/10978940/check-what-kind-of-browser-the-user-is-using) – Sadik Mar 15 '15 at 22:14

2 Answers2

2
match = navigator.userAgent.match(/(chrome|safari|firefox|msie|opera|rv:11)\/?\s*([\d\.]+)/i);

match[1] gives browser name. Also "rv:11" represents IE11.

For example, you can prepare prefixed images and use matched value as prefix:

myImg.src=match[1]+"-img1.jpg";
myImg.alt=match[1]+" Image";
0

You can do this with the below function and then just use the IF statements to set the attribute for that image.

function browsercheck() {
    var userAgent = window.navigator.userAgent;
    return (userAgent.indexOf("MSIE ") > 0 || !! userAgent.match(/Trident.*rv\:11\./));

}

var browser = browsercheck() ? 'IE' : 'Chrome';

if (browser == "IE")
{
     //Set attribute   
}

else if (browser == "Chrome")
{
     //Set attribute   
}

Use the below if you need to know exact browser

navigator.browsercheck= (function(){
    var ua= navigator.userAgent, tem,
    M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return { 'browser': M[0], 'version': M[1] };
})();

You can then query this with navigator.browserInfo.browser to get browser info or navigator.browserInfo.version if you need to know the exact version.

Credit: Browser detection in JavaScript?

Community
  • 1
  • 1
James
  • 13,679
  • 11
  • 58
  • 81
  • See edit for grabbing exact browser info. Looks like they were after Chrome or IE, but for the exact version they can tie in the added code – James Mar 15 '15 at 22:28