Changing background images with JavaScript - javascript

I'm fairly new to JavaScript and HTML and I can't seem to figure out want is wrong. This is part of an assignment I have for class so the structure/code is formatted the same way as an example the professor provided.
I'm trying to rotate between different background images.
This is what I have for the script:
var bakground = [];
background[0] = new Image();
background[0].src = "Images/blue.jpg";
background[1] = new Image();
background[1].src = "Images/chalkboard_web.jpg";
background[2] = new Image();
background[2].src = "Images/computer-scince-education.jpg";
background[3] = new Image();
background[3].src = "Images/universidad.jpg";
var i = 0;
var temp = new Image();
function wallpaper()
{
temp = background[i].src;
i++;
if(i == background.length)
i = 0;
document.body.background = 'temp';
return false;
}
This is where I'm calling the function:
<P/> <b> test changing document body background:</b>
<INPUT TYPE="button" NAME="button2" value="set background to an image"
onClick="wallpaper()" >
</P>

You are not using the "temp" variable you defined above but a string instead!
function wallpaper()
{
temp = background[i].src;
i++;
if(i == background.length)
i = 0;
document.body.background = temp;
return false;
}
Should work

There are several things.
Bugs:
type in background
you are setting document.body.background to the string 'temp' and not to your image.
you are using a closing p-tag to open the paragraph. Should be <p> instead of </P>
Other improvements:
you don't even need to create new Image(), the string of where to get the image should suffice.
you don't need to have temp as a global variable.
you can more easily modulo the iterator rather then re-setting it to 0
tags and attributes are case insensitive. It's common to use lowercase, though.
elements like input can / should have closing tags or be self-closing.
See example here:
<html>
<head>
<script>
var background = [
"https://source.unsplash.com/random",
"Images/wall.jpg",
"Images/1road.jpg"
];
var i = 0;
function wallpaper() {
document.body.background = background[i++];
i = i % background.length; // will wrap around the length. look up 'modulo' unsure
return false;
}
</script>
</head>
<body>
<p/>
<b> test changing document body background:</b>
<input type="button" name="button2" value="set background to an image"
onClick="wallpaper()" />
</p>
</body>
</html>

Related

How to access the Javascript variable value outside the script tag

I want to access the Javascript variable value outside the Javascript tag.
function getprices(input) {
return input.match(/[0-9]+/g);
}
var subtotals = get_getprices('%GLOBAL_OrderTotal%');
var Grand_total = subtotals[0];
<img height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
You'd need to update the src property on that img element. Let's suppose you gave the img an id (you don't have to, there are other ways to select it, but I'm keeping it simple):
<img id="the-image" height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
Then:
function getprices(input) {
return input.match(/[0-9]+/g);
}
var subtotals = getprices('%%GLOBAL_OrderTotal%%'); // <=== Changed to `getprices`, was `get_getprices`
var Grand_total=subtotals[0];
var img = document.getElementById("the-image");
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + Grand_total;
It looks like Grand_total will always be a number, but for the general case where it might not be, , be sure to use encodeURIComponent (it doesn't do any harm even if it is a number):
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + encodeURIComponent(Grand_total);
If you didn't use an id on the img, that's fine, you can use any CSS selector via document.querySelector. That's supported by all modern browsers, and also IE8.
Note that there are other issues with that code, though, not least that getprices looks fairly suspect.
All you need to do is to assign your value to src of img in your javascript
$("#imgNeeded").attr("src",".../"+Globalvalue)
As T.J. Crowder said. make sure you encode URI if your variable contain something other than number
You can use
document.getElementsByTagName("img")[***index of the image tag***].src = "<THE STRING>"+<THE VARIABLE>+"<THE REMAINING STRING>";
or assign an id to the <img> and use
`document.getElementById("id of the image").src = ""++"";
The problem the provided approaches share is, that how they are, your image will get loaded with the unwanted source before changed:
<html>
<head>
<script>
function getprices(input){return input.match(/[0-9]+/g)};
function changeSrc(){
var tE = document.querySelector("img[src*='saleAmount=']");
var tS = getprices('anyPrice1');
if (tE && tS) tE.src += encodeURIComponent(tS[0]);
};
</script>
</head>
<body onload = 'changeSrc()'>
<img height = '0' width = '0' border = '0' src = 'http://JUSTTOSHOWtesting.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=' onerror = 'console.log(this.src)'>
</body>
Your console will log two calls:
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount= net::ERR_NAME_NOT_RESOLVED
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=1 net::ERR_NAME_NOT_RESOLVED
So what you could do is placing a placeholder, until you have the source you need:
<html>
<head>
<script>
function getprices(input){return input.match(/[0-9]+/g)};
function createSrc(){
var tE = document.querySelector("ins[src*='saleAmount=']");
var tS = getprices('anyPrice1');
if (tE && tS){
var tI = document.getElementById('iPlaceholder');
if (!tI){
tI = document.createElement('img');
tI.id = 'iPlaceholder';
tI.onerror = function(){console.log(this.src)};
tE.parentNode.insertBefore(tI, tE.nextSibling);
};
tI.src = tE.getAttribute('src') + encodeURIComponent(tS[0]);
};
};
</script>
</head>
<body onload = 'createSrc()'>
<ins src = 'http://JUSTTOSHOWtesting.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount='></ins>
</body>
</html>
Now your console will merely log one call:
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=1 net::ERR_NAME_NOT_RESOLVED

getElementById() is null?

So I am trying to make a JavaScript program that will take a URL for an image and then put it onto the page while creating an <img> tag so that I can just continue pasting as many photos as I want. Here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Low-Budget Online Album</title>
<meta charset="utf-8">
<script>
function init() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
window.onload = init;
function buttonClick() {
var imageSource = document.getElementById("imageInput").value;
if (imageSource == "") {
alert("Please enter the source for an image.");
}
else {
var newImage = document.createElement("img");
var newSrc = document.getElementById("newImage").src= imageSource;
imageInput.value = "";
}
}
</script>
</head>
<body>
<input type="text" id="imageInput" size="40" placeholder="Image Source">
<input type="button" id="addButton" value="Add Image">
<img id="images" src="">
</img>
</body>
</html>
My problem is, is that when I put int a URL (or picture src from my PC) it says that TypeError: document.getElementById(...) is null, and points to line 20, being my
var newSrc = document.getElementById("newImage").src= imageSource;
line. Any ideas?
Use this
else {
var newImage = document.createElement("img"); //this line creates element <img> element in the dom.
newImage.setAttribute("id", "newImage");
newImage.src= imageSource;
document.body.appendChild(newImage);//adds element <img src="a.jpg" id='newImage'>to the dom.
imageInput.value = "";
}
Understand what mistake you have done above:
1.First you created element and assign to a variable newImage
var newImage=document.createElement("img");
2.You are calling
document.getElementById('newImage');
Here newImage as element that you created and in the dom there is no element with id as newImage so you were getting null.
do you mean something like this:
function init() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
window.onload = init;
function buttonClick() {
var imageSource = document.getElementById("imageInput").value;
if (imageSource == "") {
alert("Please enter the source for an image.");
}
else {
var newImage = document.createElement("img");
newImage.src= imageSource;
newImage.setAttribute("id", "newImage");
imageInput.value = "";
document.body.appendChild(newImage);
}
}
Demo:: jsFiddle
var newImage = document.createElement("img");
var newSrc = document.getElementById("newImage").src= imageSource;
Become:
var newImage = document.createElement("img");
newImage.setAttribute('id','newImage');
var newSrc = document.getElementById("newImage").src = imageSource;
in mdn you can see that createElement only create element and not add it to DOM. So if you want add created element you need change your code like this
var newImage = document.createElement("img");
newImage.id = "newImage";
document.body.appendChild(newImage);
after this line will work
var newSrc = document.getElementById("newImage").src= imageSource;
but you don't need get find it if you already have this image in newImage variable, so this line you can change like
var newSrc = newImage.src= imageSource;
UPDATE
Possibly you need use className instead of id because id should be unique on page, but as i understand you want add many images

Dynamically generating a button using DOM and editing onclick event

I trying to generate an input (type="button") and setting the onclick-Event to a function, which should hand over a parameter. The whole object should be appended to a div and thats it. Basically this is my try, but I can't see why it does not work.
I pasted the code to jsfiddle, hence its easier for you to reproduce. Click here.
What am I'm doing wrong? I'm learning it by trial and error, so please explain whats wrong. Thanks a lot!
[edit] for the case jsfiddle will be down one day, here is the code I tried to run... :)
<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript" language="javascript">
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
var h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}​
</script>
</head>
<body>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
</body>
</html>
Here is the fixed fiddle for you.
var h[i] = ... is invalid JavaScript.
What you write in the "JavaScript" frame on jsfiddle is executed onload, so this code is not yet present when the HTML you provide is executed (and neither is the addButton() function).
<script>
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
Try using h.push(...) instead of trying to send to a non created element in the array
var x = document.getElementById('pagination');//pagination is an empty div in html
var y ='';
for(var i = 0; i <= (pageMax); i++){
y = y+"<a id ='pageNumber"+i+"' onclick='changePage("+(i+1)+");'>"+(i+1)+"</a>\n ";
} x.innerHTML=y }
i used this to make a pagination for a table. The function will create a row of numbers until button max. 'changePage("+(i+1)+"); ... will call a function and send the i index(number that the page is) of the pagenumber. also i dynamically create a id unique for each number.

getElementById() .innerHTML/.src

I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great
Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>

Javascript text file reader doesnt work the first time

I got a webpage with some homemade search engine which is supposed to look for some data in a server-side text file. I use JS to parse this file, it works well except for the very 1st time I use it... The culprit seems to be my fetchText() function which doesnt return anything the first time. Note that if I add a alert() inside the fetchText() it works correctly (see note in JS source code). I guess the IFRAME is not fully loaded or something. What can I do ?
Webpage code
<form style="margin-top:15px; margin-left:15px;width:200px;">
<input type="text" value="NGR_" id="srcTxtInput" style="margin-top:0px;margin-left:0px;width:100px;"/>
<input type="button" value="Go" onclick="SearchString('./Coordinates.txt')" />
</form>
<div id="searchResults" style="vertical-align:right;margin-top:25px;">
<select size="4" id="select_list" onchange="Selec_change();" ondblclick="Selec_change();" style="visibility: hidden; width:250px;margin-left:8px;" ></select>
<img id="closeImg" src="./close.png" height="15px" width="15px" style="opacity:0.5;visibility:hidden; margin-left:235px;margin-bottom:5px;margin-top:5px;vertical-align:top;" alt="Close results" title="Close results" onclick="HideSearch();" onmouseover="this.style.cursor='pointer';"/>
</div>
JS code
function SearchString(txtFile){
var slist = document.getElementById('select_list');
var str = trim(document.getElementById('srcTxtInput').value.toUpperCase());
if(str == "" ){
slist.options.length = 0; //empty list
HideSearch();
exit;
}
var txt = fetchText(txtFile);
//DO SOMETHING
}
function fetchText(txtFile) {
var d = document;
var txtFrame = d.getElementById('textReader');
txtFrame.src = txtFile;
**//Note that if I add *alert(txtFrame.src)* here the function works the 1st time**
var text = '';
if (txtFrame.contentDocument) {
var d = txtFrame.contentDocument;
text = d.getElementsByTagName( 'BODY')[ 0].innerHTML;
}
else if (txtFrame.contentWindow) {
var w = txtFrame.contentWindow;
text = w.document.body.innerHTML;
}
return text;
}
Since loading page content like that is an asynchronous operation, you can't expect the contents to be there immediately after setting the "src" attribute of your <iframe>. You'll have to put the code that searches through the text in a "load" event handler on the frame document.
That means you'll write something like:
fetchText(textFile, function(theText) {
// DO SOMETHING
});
and modify "fetchText()" to be more like this:
function fetchText(txtFile, whenLoaded) {
var d = document;
var txtFrame = d.getElementById('textReader');
txtFrame.onload = function() {
var text = '';
if (txtFrame.contentDocument) {
var d = txtFrame.contentDocument;
text = d.getElementsByTagName( 'BODY')[ 0].innerHTML;
}
else if (txtFrame.contentWindow) {
var w = txtFrame.contentWindow;
text = w.document.body.innerHTML;
}
whenLoaded(text);
};
txtFrame.src = txtFile;
}

Categories