How to Change Image on the basis of browser detection - javascript

I am facing one issue in my HTML page actually I need to implement the below-
I need to change my image on the basis of Browser change .So, when I am browsing with Chrome it should load Image1 or if I am browsing with IE then load Image2. Please find the below code which I am using but it is not working for me
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script language="javascript">
function browsercheck() {
var userAgent = window.navigator.userAgent;
return (userAgent.indexOf("MSIE ") > 0 || !!userAgent.match(/Trident.*rv\:11\./));
}
function displayImage() {
debugger;
var browser = browsercheck() ? 'IE' : 'Chrome';
if (browser == "IE") {
document.getElementById("image").setAttribute("src", "Image1.jpg");
}
else if (browser == "Chrome") {
document.getElementById("image").setAttribute("src", "Image2.jpg");
}
}
</script>
</head>
<body">
<img id="image" this.src="displayImage()" alt="can't display picture" />
</body>

It's simpler to maintain if you distribute responsibilities between CSS and JavaScript. Let each do what it's meant to.
<script>
var browser = browsercheck() ? 'ie' : 'chrome';
document.body.className += ' ' + browser; // vanilla JS
// $('body').addClass(browser); // jQuery version
</script>
<style>
.image {
background-image: url("regular.jpg");
}
.chrome .image {
background-image: url("chrome_specific.jpg");
}
.ie .image {
background-image: url("ie_specific.jpg");
}
</style>

This JSFiddle shows example of Browser Detection https://jsfiddle.net/311aLtkz/
I think script did not work for you, because you had a function, and you did not use that function on page. Edited code should work when page in opened
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") {
document.getElementById("image").setAttribute("src", "Image1.jpg");
console.log("IE");
}
else if (browser == "Chrome") {
document.getElementById("image").setAttribute("src", "Image2.jpg");
console.log("Chrome");
}

Related

Page redirect not loading

For some reason, this page won't go to the mobile or desktop page when I use it! Here is the code:
<html>
<head>
<title>Loading...</title>
</head>
<script>
window.onload = function() {
var iOS = ( navigator.userAgent.match(/iPad|iPhone|iPod/g) ? true : false );
if (iOS == true) {
window.location.href="http://m.lifewithzooza.x10host.com/";
} else {
window.location.href="http://lifewithzooza.x10host.com/wordpress/";
}
</script>
<body bgcolor="#FFFFFF">
Loading...
</body>
</html>
Sorry, this is my first time on Stack Overflow, so I'm not familiar with some stuff. Thanks.
You are missing the closing } for onload function. Update code to following.
window.onload = function() {
var iOS = ( navigator.userAgent.match(/iPad|iPhone|iPod/g) ? true : false );
if (iOS == true) {
window.location.href="http://m.lifewithzooza.x10host.com/";
} else {
window.location.href="http://lifewithzooza.x10host.com/wordpress/";
}
}
You have missing } . so its not working. You have missed } for the window.onload = function() { //your code goes here }
Please check running code here
window.onload = function() {
var iOS = ( navigator.userAgent.match(/iPad|iPhone|iPod/g) ? true : false );
if (iOS == true) {
window.location.href="http://m.lifewithzooza.x10host.com/";
} else {
window.location.href="http://lifewithzooza.x10host.com/wordpress/";
}
}
<html>
<head>
<title>Loading...</title>
</head>
<body bgcolor="#FFFFFF">
Loading...
</body>
</html>
2 problems:
You've put your script element in the wrong place, in the middle of nowhere. The script tag must be under body or head and nothing else. As said at W3: The SCRIPT element places a script within a document. This element may appear any number of times in the HEAD or BODY of an HTML document.
You also missed a } on your onload function:
<html>
<head>
<title>Loading...</title>
<script>
window.onload = function() {
var iOS = ( navigator.userAgent.match(/iPad|iPhone|iPod/g) ? true : false );
if (iOS) {
window.location.href="http://m.lifewithzooza.x10host.com/";
} else {
window.location.href="http://lifewithzooza.x10host.com/wordpress/";
}
}
</script>
</head>
<body bgcolor="#FFFFFF">
Loading...
</body>
</html>

Angular ng-auth-token does not close the window on redirect safari

I am using ng auth token and rails devise token, when i am login in ios safari the window is stuck on the "redirecting" window and does not close the window.
This is the code that run to close the window:
<!DOCTYPE html>
<html>
<head>
<script>
var usingExternalWindow = function() {
var nav = navigator.userAgent.toLowerCase(),
ieLTE10 = (nav && nav.indexOf('msie') != -1),
ie11 = !!navigator.userAgent.match(/Trident.*rv\:11\./);
return !(ieLTE10 || ie11);
}
if (usingExternalWindow()) {
window.addEventListener("message", function(ev) {
if (ev.data === "requestCredentials") {
ev.source.postMessage({
<%= yield %>
}, '*');
window.close();
}
});
} else {
window.location.href = "<%= #auth_origin_url %>";
}
</script>
</head>
<body>
<pre>
Redirecting...
</pre>
</body>
</html>
In all other browsers this is working fine and here its seems like the postMessage does not send to the new tab.

Browser Detection and Compatibility Checking with Java Script

I am trying to detect browser types and IE compatibility from user agent and redirect accordingly. It works only in IE but not in Firefox and Chrome. I am still looking around the solution and cannot figure out yet.
<html>
<head>
<title>Testing </title>
<script src="UserAgent.js" type="text/javascript"></script>
</head>
<body>
<div id="results">Output</div>
<script type="text/javascript">
if (UserAgent.firefox){
window.location.href("http://www.yahoo.com");
}
if (UserAgent.compatibilityMode) {
window.location.href("http://192.168.10.236/iecorrect.html");
} else {
window.location.href("http://www.apple.com");
}
</script>
</body>
</html>
UserAgent.js
if (typeof jQuery == 'undefined') {
document.write("\<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'>\<\/script>");
}
// Create new object
var UserAgent = {
init: function () {
// Get the user agent string
var ua = navigator.userAgent;
this.compatibilityMode = false;
this.firefox = ua.toLowerCase().indexOf("firefox") > -1;
this.chrome = ua.toLowerCase().indexOf("chrome") > -1
if (ua.indexOf("MSIE 7.0") > -1) {
this.compatibilityMode = true;
}
}
};
// Initialize the object
ieUserAgent.init();
Change your window.loacation.href calls to the below code:
if (UserAgent.compatibilityMode) {
window.location.href = "http://192.168.10.236/iecorrect.html";
} else {
window.location.href = "http://www.apple.com";
}
You wrote them like you would write jQuery :)
To check for IE and/or a specific version of IE you are better off using conditional statements.
http://www.quirksmode.org/css/condcom.html

checking the browser type within function not working in Javascript

In my page, I used javascript function for block with a condition. If the browser is IE8 then the style will be like this or use style within else. But if I used the below condition, the function not works. Anyone please help me to solve this issue
function addnew(type)
{
type=parseInt(type)+1;
var isOpera, isIE = false;
if(typeof(window.opera) != 'undefined'){isOpera = true;}
if(!isOpera && navigator.userAgent.indexOf('Internet Explorer')){isIE = true);
var mydiv = document.createElement("div");
mydiv.setAttribute("id",name5);
if(!IE){
mydiv.setAttribute("style","width:110px;height:80px;background-image:url(images/transparent.png);float:left;text-align:center;border:1px solid #ccc;");
}
else
{
mydiv.style.setAttribute('cssText', "width:110px;height:80px;background-image:url(images/transparent.png);float:left;text-align:center;border:1px solid #ccc;");
}
}
<input id="addchoice" type=button value="Add New Entry" onclick="addnew(document.forms['addpoll']['choicecount'].value);">
There is a cleaner way to target specific versions of Internet Explorer, Conditional Comments.
Example:
<!--[if IE 8]>
<style type="text/css">
.my-div-class-here {
width:110px;
height:80px;
... }
</style>
<![endif]-->
function addnew(type)
{
var isOpera, isIE = false;
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
if (ieversion==8)
isIE = true;
}
if(isIE)
{
//code for IE
}
else
{
//code for other browsers
}

How can i print a pdf in google chrome?

I have a pdf associated with a button . When i click the button i want to get the pdf printed. This is how my button is coded :
<input type="submit" class="btn-red" value="Print"
name="Submit" id="printbtn"
onclick="printPDF('http://www.irs.gov/pub/irs-pdf/fw4.pdf')" />
Now my print functionality works like this :
function printPDF(pdfUrl)
{
if ((navigator.appName == 'Microsoft Internet Explorer') )
window.print(pdfUrl,"_self");
else
{
var w = window.open(pdfUrl,"_self");
w.print();
w.close();
}
}
The problem is , it's working fine in IE and Fire fox , but does not work in chrome. In ie and Firefox, it opens up the xps printer option, but in chrome , it just opens up a new print window, with the print preview of the div and not the pdf . But i want the xps option to be opened up here.
EDIT : In chrome when i try to print , only the html element comes as preview and not the pdf. I am using chrome version : 20.0.1132.57
How can i get around this peculiarity ? kindly help .
This worked for me and didn't require a host HTML file. The key was to wait for onload:
For a link like this:
<a class="print-pdf-link" href="/your/pdf.pdf">Print PDF</a>
I used javascript:
$('a.print-pdf-link').click(function () {
var w = window.open($(this).attr('href'));
w.onload = function () {
w.print();
};
return false;
});
I had to do the same thing and I used a different approach, one that for me worked in both Chrome and Firefox.
My solution involved a print.html helper file, that received the PDF file's url as a GET type parameter, then loaded the pdf inside an iframe. Then it kept checking to see if the pdf had completely loaded (binding the check to the onload event did not work) and on completion it triggered the print method.
Here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<title>Print Page</title>
<meta name="title" content="Print" />
<script>
(function (window, document, undefined) {
var printy = {
urlGET: function (param) {
var params = document.URL.split('?');
if(params.length > 1) {
params = params[1].split('&');
for (var i = 0, len = params.length; i < len; i++) {
if (params[i].split('=')[0] === param) {
return params[i].split('=')[1];
}
}
}
return null;
},
init: function () {
var self = this;
window.onload = function () {
var src = self.urlGET('path');
//creating an iframe element
var ifr = document.createElement('iframe');
document.body.appendChild(ifr);
// making the iframe fill the viewport
ifr.width = '100%';
ifr.height = window.innerHeight;
// continuously checking to see if the pdf file has been loaded
self.interval = setInterval(function () {
if (ifr.contentDocument.readyState === 'complete') {
clearInterval(self.interval);
// doing the actual printing
ifr.contentWindow.print();
}
}, 100);
ifr.src = src;
}
}
}
printy.init();
})(window, document, undefined);
</script>
</head>
<body>
</body>
</html>
This solution is not tested on IE though. We use Macs at work so it was not an option.
In order to do the printing, I use it by calling an URL like this: http://example.com/print.html?path=docs/myfile.pdf

Categories

Resources