Javascript - Changing button image depending on device - javascript

I am trying to display the correct button and link depending on what device the user browses to a page on. If android display android app store button if ios display apple store button.
I cannot seem to get it to swap at all even though im making the function default to swap it from android to apple button.
Here is the code:
<html>
<head>
<script type="text/javascript">
var uagent = navigator.userAgent.toLowerCase();
var apple = "/images/ios.jpg";
var android = "/images/android.jpg"
function DetectDevice() {
var but = document.getElementById("AppButton");
if(useragent.search("iphone") || useragent.search("ipod") || useragent.search("ipad")) {
toswap.src = apple;
alert("apple");
} else if(useragent.search("android")) {
toswap.src = android;
alert("android");
}
but.src = apple;
}
DetectDevice();
</script>
<title>Device Detection</title>
</head>
<div id="butttons">
<img src="images/android.jpg" name = "AppButton" id="AppButton"/>
</div>

Two issues:
First, your function needs to run after the button has loaded because
document.getElementById("AppButton");
is returning nothing at the moment.
Secondly, you should probably change 2 instances of toswap.src to but.src.

I don't know where var toswap refers to. Try this:
var uagent = navigator.userAgent.toLowerCase();
var apple = "/images/ios.jpg";
var android = "/images/android.jpg"
function DetectDevice() {
var but = document.getElementById("AppButton");
if(useragent.search("iphone") || useragent.search("ipod") || useragent.search("ipad")) {
but.src = apple;
alert("apple");
} else if(useragent.search("android")) {
but.src = android;
alert("android");
} else{
but.src = apple; // this is default
}
}
</script>
<div id="butttons">
<img src="images/android.jpg" onload="DetectDevice();" name = "AppButton" id="AppButton"/>
</div>

useragent is not defined either. You may have meant to use uagent which you defined, or you may have meant to rename your variable.

Related

Popunder run automatically

I have a code that inserts a popunder into all the links on my page.
However, I need something that makes this popunder / tabunder run automatically, regardless of the click.
I've tried in many ways but I can't.
Can someone help me?
window.onload = function() {
var puURL = 'http://google.com';
var puTS = Math.round(+new Date()/1000);
console.log('T.'+localStorage.puTS+'/'+puTS);
if (typeof localStorage.puTS == 'undefined' || parseInt(localStorage.puTS) <= (puTS - 3600)) {
var links = document.getElementsByTagName('a');
for(var i = 0, len = links.length; i < len; i++) {
links[i].onclick = function (e) {
var puHref = this.getAttribute("href");
var puTarget = this.getAttribute("target");
if (puHref !== '#' && puHref !== 'javascript:void(0)') {
e.preventDefault();
if (puTarget == '_blank') {
window.open(window.location.href);
}
window.open(puHref);
window.location.href = puURL;
localStorage.puTS = puTS;
}
}
}
}
};
I have placed your script locally under the HEAD Tag section and the function is triggered when I open the HTML file. I assume that the issue lays in the script placement.
If your script is stored outside the project (is external), make sure that you navigate to the correct root and double-check for spelling. Here is an example:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="project/javascript_folder/myscript.js"></script>
</head>
<body>
...
</body>
</html>
You can check out W3Schools File Paths for more detail.
If you open your browsers DEV-TOOLS (by pressing the Right-Click button on your mouse while you hover over the page) and navigate to the console section, you should see the successful output from your function:
In my case, it is T.undefined/... where "..." represents a randomly generated number in the length of 10.

Why do I get null when I getElementById?

I'm new to JS, and reading Javascript Dom, I'm trying to figure out one of the example in my book!
here is my html code
<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset="utf-8" />
<title>Image Gallery</title>
</head>
<body>
<script type = "text/javascript" src="showPic.js"></script>
<h1>Snapshots</h1>
<ul id = "image">
<li>
Fall
</li>
<li>
Sunshine
</li>
<li>
Green
</li>
<li>
Filter
</li>
</ul>
<img id = "placeholeder" src="images/rise.jpg" alt = "my image gallery"/>
<p id="description"> Choose an image</p>
</body>
</html>
here is my javaScript code
function showPic(whichPic) {
var source = whichPic.getAttribute("href");
var placeholder = document.getElementById("placeholeder");
placeholder.setAttribute("src", source);
description.firstChild.nodeValue = text;
}
var text = whichPic.getAttribute("title");
var description = document.getElementById("description");
function perpareGallery() {
var gallery = document.getElementById("image");
var links = gallery.getElementsByTagName("a");
for(var i = 0 ; i<links.length; i++) {
links[i].onclick = function() {
showPic(this);
return false;
}
}
}
my code didnt getting anything from id = image. and I checked many times dont know what is wrong....
There seems to be no code that actually runs the perpareGallery() function.
After you fix that, it might still not work if you run perpareGallery() before the elements in HTML (like your a elements) are parsed and rendered. So, you might want to do something like:
window.onload = prepareGalery;
Although there are way better ways to set-up events, this will run your function after all HTML is parsed.
Two advices on how to track down your issue:
1) All browsers have a so called javascript console. It shows you all syntax error with your code. For firefox and chromium the keyboard shortcut F12 turns it on/off
If you run your code and open the javascript console you'll see this error:
ReferenceError: whichPic is not defined
In your example it looks as if the line var text = whichPic.getAttribute("title"); belongs to the function showPic(whichPic), but it doesn't.
2) You should format your code to not get lost. Your current code formatted:
function showPic(whichPic) {
var source = whichPic.getAttribute("href");
var placeholder = document.getElementById("placeholeder");
placeholder.setAttribute("src", source);
description.firstChild.nodeValue = text;
}
var text = whichPic.getAttribute("title");
var description = document.getElementById("description");
function perpareGallery() {
var gallery = document.getElementById("image");
var links = gallery.getElementsByTagName("a");
for(var i = 0 ; i<links.length; i++) {
links[i].onclick = function() {
showPic(this);
return false;
}
}
}
If you now take a look to the formatted code, it no longer looks as if whichPic is used inside of showPic(whichPic) but outside of the scope. The error makes perfectly sense.
You might want to move it inside of the function, before you use it.

Changing useragent if ipad

What I want to do is detect if the user is using an iPad, then change the useragent to iPhone. But I also want to ensure the page detects this change before page load..
I've tried doing this but no luck.
<script type="text/javascript">
var navigator = new Object;
var userAgent = HttpContext.Current.Request.UserAgent.ToLower();
if (userAgent.Contains("ipad;"))
{
navigator.userAgent = 'iPhone';
}
</script>
The userAgent is readonly you can not set it to anything.
You are using HttpContext.Current.Request.UserAgent.ToLower(); which is not valid javascript. This is c# which your browser can not execute.
Instead look at the navigator.userAgent
var nav = '';
if (navigator.userAgent.indexOf('iPad') != -1) {
nav = 'Its an iPad';
} else {
nav = 'Its some other device';
}
console.log(nav);

Range Selection and Mozilla

I would like to specify that firefox select a range. I can do this easily with IE, using range.select();. It appears that FFX expects a dom element instead. Am I mistaken, or is there a better way to go about this?
I start by getting the text selection, converting it to a range (I think?) and saving the text selection. This is where I'm getting the range from initially:
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) == false){
selectedText=selectedText.toString();
}
origRange = userSelection;
I later change the selection (successfully). I do so by range in IE and by a dom ID in ffx. But after I do that, I want to set back the selection to the original selection.
This works like a charm in IE:
setTimeout(function(){
origRange.select();
},1000);
I would like to do something like this in FFX:
var s = w.getSelection();
setTimeout(function(){
s.removeAllRanges();
s.addRange(origRange);
},1000);
Unfortunately, FFX has not been cooperative and this doesn't work. Any ideas?
The short answer is: IE and other browsers differ in their implementations of selecting text using JavaScript (IE has its proprietary methods). Have a look at Selecting text with JavaScript.
Also, see setSelectionRange at MDC.
EDIT: After making a little test case, the problem becomes clear.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addRange test</title>
<style>
#trigger { background: lightgreen }
</style>
</head>
<body>
<p id="test">This is some (rather short) text.</p>
<span id="trigger">Trigger testCase().</span>
<script>
var origRange;
var reselectFunc = function () {
var savedRange = origRange;
savedRange.removeAllRanges();
savedRange.addRange(origRange);
};
var testCase = function () {
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) === false){
/* you shouldn't do this kind of browser sniffing,
users of Opera and WebKit based browsers
can easily spoof the UA string */
selectedText=selectedText.toString();
}
origRange = userSelection;
window.setTimeout(reselectFunc, 1000);
};
window.onload = function () {
var el = document.getElementById("trigger");
el.onmouseover = testCase;
};
</script>
</body>
</html>
When testing this in Firefox, Chromium and Opera, the debugging tools show that after invoking removeAllRanges in reselectFunc, both savedRange and origRange are reset. Invoking addRange with such an object causes an exception to be thrown in Firefox:
uncaught exception: [Exception...
"Could not convert JavaScript argument
arg 0 [nsISelection.addRange]"
nsresult: "0x80570009
(NS_ERROR_XPC_BAD_CONVERT_JS)"
location: "JS frame ::
file:///home/mk/tests/addrange.html ::
anonymous :: line 19" data: no]
No need to say that in all three browsers no text is selected.
Apparently this in intended behaviour. All variables assigned a (DOM)Selection object are reset after calling removeAllRanges.
Thank you Marcel. You're right, the trick is to clone the range, then remove the specific original range. This way we can revert to the cloned range. Your help led me to the below code, which switches the selection to elsewhere, and then back according to a timeout.
I couldn't have done it without you, and grant you the correct answer for it :D
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addRange test</title>
<style>
#trigger { background: lightgreen }
</style>
</head>
<body>
<p id="switch">Switch to this text</p>
<p id="test">This is some (rather short) text.</p>
<span id="trigger">Trigger testCase().</span>
<script>
var origRange;
var s = window.getSelection();
var reselectFunc = function () {
s.removeAllRanges();
s.addRange(origRange);
};
var testCase = function () {
// Before modifying selection, save it
var userSelection,selectedText = '';
if(window.getSelection){
userSelection=window.getSelection();
}
else if(document.selection){
userSelection=document.selection.createRange();
}
selectedText=userSelection;
if(userSelection.text){
selectedText=userSelection.text;
}
if(/msie|MSIE/.test(navigator.userAgent) === false){
/* you shouldn't do this kind of browser sniffing,
users of Opera and WebKit based browsers
can easily spoof the UA string */
selectedText=selectedText.toString();
}
origRange = userSelection;
var range = s.getRangeAt(0);
origRange = range.cloneRange();
var sasDom = document.getElementById("switch");
s.removeRange(range);
range.selectNode(sasDom);
s.addRange(range);
window.setTimeout(reselectFunc, 1000);
};
window.onload = function () {
var el = document.getElementById("trigger");
el.onmouseover = testCase;
};
</script>
</body>
</html>

Using a bookmarklet to track a package

I'm trying to write a bookmarklet that tracks a package in the mail. First it checks to see if the tracking page is open, if not it opens it in a new tab, and then sets the value of the form to the tracking number. Finally, it submits the form. What I'm so far unable to do is set the value of the form in the case where the bookmarklet opens up a new tab.
Here's what I have:
javascript: (function(){
var trackingNumber = "/*tracking number*/";
var a = document.forms.trackingForm;
if ('http://fedex.com/Tracking' == document.location) {
trackingForm.trackNbrs.value = trackingNumber;
document.forms.trackingForm.submit();
}
else {
window.open('http://fedex.com/Tracking');
this.window.onload = function(){ //This seems to be the problem
trackingForm.trackNbrs.value = trackingNumber;
onload(document.forms.trackingForm.submit());
}
}
})();
Any ideas?
window.open opens a new window, so if this is going to work at all (I have little experience with bookmarklets), you would have to address the new window directly. Something like this:
else {
new_window = window.open('http://fedex.com/Tracking');
new_window.onload = function(){
new_window.document.trackingForm.trackNbrs.value = trackingNumber;
new_window.document.forms.trackingForm.submit();
// I didn't get at all what the onload() was for, re-add if necessary
}

Categories

Resources