Change picture in an array with button click - javascript

I have a question concerning pictures in an array. I am able to change the picture with a click, but only once. This is my code with some example pictures. There are a lot of tutorials on the net but maybe too complex for me so I created a simple thing.
<html>
<head>
<script type="text/javascript">
//here I am creating my array
var myPicture = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
]
// this should be the function and I think here is the error
function nextPic() {
myPicture[1] = document.images;
}
</script>
</head>
<body>
<img src="http://www.java2s.com/style/download.png" width="107" height="98" />
<form>
<input type="button" onclick="nextPic()" value="Change image">
</form>
</body>
</html>
The simple question is, what do I have to change in my code to show the second, third, x pic with one click. Or is there an simple jQuery function for it?

Here's a working example: http://jsbin.com/dubuhizucu/edit?html,console,output
so a couple of things..
1) you need a variable to keep track of where you are in your pictures array.
2) on click, increment that variable from step 1. then, check if it's bigger than the length of your pictures array. if it is then we need to reset it back to 0.
3) simply set the src attribute on the image to the URL from your pictures array, setting the index to whatever the value of counter is!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="target" src="http://www.java2s.com/style/download.png" width="107" height="98" />
<input type="button" onclick="nextPic()" value="change image" />
<script>
var target = document.getElementById('target');
var counter = 0;
var myPictures = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
];
function nextPic() {
counter += 1;
if (counter > myPictures.length -1) {
counter = 0;
}
target.src = myPictures[counter];
}
</script>
</body>
</html>

Give your img an id: id="img1"
Create a global variable, for example:
var x = 0;
A global variable is declared in the scope of the entire file, meaning it is not surrounded by any functions, loops, if statements, etc. Your array, myPicture is global.
Then in your function:
function nextPic()
Write instead:
function nextPic(){
// Increment x by 1, x = x + 1
x++;
// Check if on last element of array, change x to first
if(x >= myPicture.length) {
x = 0;
}
// Use variable, declared as number, to access img in array
document.getElementById("img1").src = myPicture[x];
}
If we do not check if x is greater than or equal to the array length then once we have iterated through each image we would attempt to access a null value of the array, one that does not exist.
Your example has an array length of 3, therefore it has indices 0-2. We cannot access any index greater than 2, therefore we set x back to 0.

Your nextPic function is a little bit backwards.
Each time nextPic is called, you're setting the second element in your myPicture array equal to document.images. That's not what you want. You want to set the src of the image (document.images[0]) equal to the next image URL, so you need a way to keep track of what image you're working with (currentImageIndex).
Here's a working example:
var myPicture = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
];
var currentImageIndex = 0;
function nextPic() {
currentImageIndex = (currentImageIndex + 1) % myPicture.length;
document.images[0].src = myPicture[currentImageIndex];
}
<img src="http://www.java2s.com/style/download.png" width="107" height="98" />
<form>
<input type="button" onclick="nextPic()" value="Change image">
</form>

Related

Changing background images with 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>

"Writing" inside a HTML page using JS and JS scope

I'm developing a program which basically just receives input from the user twice (risk carrier and sum, but that's just a placeholder to make my program less abstract), groups those two values together and then repeats the contents in a loop. See the code below.
<head>
<script type="text/javascript">
function fillArray(){
document.getElementById("danke").innerHTML = "Thanks for specifying the amount of entries.";
var numberOfEntries = parseInt(document.getElementById('input0').value);
var i = 0;
var myArrA = [];
var myArrB = [];
var x = " ";
while(i<numberOfEntries){
var neuRT = prompt("Enter a risk carrier");
myArrA.push(neuRT);
var neuRH = prompt("Enter a risk sum");
myArrB.push(neuRH);
i++;
}
for(i = 0; i<anzahlEintraege; i++){
x = myArrA[i] + " carries a risk of " + myArrB[i];
document.getElementById("test").innerHTML = x;
}
}
</script>
</head>
<body>
<h1>risk assessment</h1>
<input type="text" id="input0" />
<button type="button" onclick="fillArray()">Number of entries</button> <p id="danke"></p>
<button type="button" onclick="untilNow()">Show all entries so far</button>
<br />
<br />
<div id="test"></div>
</body>
</html>
My issues are:
1.) I want to display the array by writing into an HTML element, which I attempted in the for-loop. Pop-ups are to be avoided. How can I loop through HTML elements, such as demo1, demo2, demo3 etc.? I can't just write <p id="demo" + i></p>. What other options are there?
2.) Say I want to make use of the untilNow() function. The scope of my arrays is limited to fillArray(). Do I need to "return" the arrays to the untilNow() function as parameters?
Thanks everyone!!!
The problem with your current code is that you're replacing the html by the last value in every loop. You're using = rather than +=. So, a quick fix would be to replace:
document.getElementById("test").innerHTML = x;
by:
document.getElementById("test").innerHTML += x;
An example of how you could wrap an array of strings in HTMLElements and add them to your document (note that there are many other ways/libraries to achieve the same result):
var myStrings = ["Hello", "stack", "overflow"];
// Two performance rules:
// 1. Use a fragment to prevent multiple updates to the DOM
// 2. No DOM queries in the loop
var newContent = myStrings.reduce(function(result, str) {
var li = document.createElement("li");
var txt = document.createTextNode(str);
li.appendChild(txt);
result.appendChild(li);
return result;
}, document.createDocumentFragment());
// Actually add the new content
document.querySelector("ul").appendChild(newContent);
<ul class="js-list"></ul>

Javascript move picture to the right where the first goes to the back comes to the front with the click of a button

I am trying to create a JavaScript code that has 3 images up when a button is pushed it looks like they are all moving right. So far I am super lose on the JavaScript part of the code. I can't get it to move, or the button to work.
HTML:
<head>
<script src="switchright.js"> </script>
<body>
<h1 style="text-align:center">Image Switcher</h1>
<center>
<img src="../images/smile.png" id=smile>
<img src="../images/plain.png" id=plain>
<img src="../images/wink.png" id=wink>
<br>
<button type="button" id=theButton>Switch Right</button>
</center>
</body>
</head>
Javascript:
theButton.onclick = function pictureChange(){
document.getElementById('smile').src="../images/wink.png";
}
theButton.onclick = function pictureChange(){
document.getElementById('plain').src="../images/smile.png";
}
theButton.onclick = function pictureChange(){
document.getElementById('wink').src="../images/smile.png";
}
As I understood - you have 3 images in a row and you want to change their sources circularly by clicking the button.
Hope this helps ( by the way - I think you should embrace the value of id attribute in double quotes )
// this will iterate from 0 to 2 and represents
// the current position of wink
var position = 0;
// save the links to files in an array
var images = ["../images/wink.png", "../images/smile.png", "../images/smile.png"];
// document.getElementById() are expensive in time
// so better to save the references to the objects
// and not find them every click
var smile = document.getElementById('smile');
var plain = document.getElementById('plain');
var wink = document.getElementById('wink');
theButton.onclick = function() {
// here you now depend on the position values that
smile.src = images[position % 3];
plain.src = images[(position + 1) % 3];
wink.src = images[(position + 2) % 3];
// increments the position variable and checks
// that it deosn't become beggier that 2
position++;
if (position > 2) {
position = 0;
}
}
Please mind that you can change the sources in the images array ( if there would be some issues with that ).
Switch the sources in just one function like this:
window.slide = function(){
var store = document.getElementById('wink').src;
document.getElementById('wink').src = document.getElementById('plain').src;
document.getElementById('plain').src = document.getElementById('smile').src;
document.getElementById('smile').src = store;
}
.small {
width: 25px;
height: 25px;
}
<h1 style="text-align:center">Image Switcher</h1>
<center>
<img class="small" src="http://www.costarricense.cr/pagina/radiogigante/index_files/image007.gif" id="smile">
<img class="small" src="http://www.skip-hop.co.uk/images/skip-hop-number-2.gif" id="plain">
<img class="small" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/L3lo.gif" id="wink">
<br>
<button type="button" onclick="slide()">Switch Right</button>
</center>

Random Image Display, Without Repeat, with Javascript

I know there are already a few questions like this, but I just can't seem to apply any of the answers (this is my first time making anything like this at all). I currently have a page that, when a button is pushed, a random image appears (thanks to some of the great posts on here, this is actually working). My issue is, the random number has a lot of repeats prior all the images being seen. I am wanting to make it where all images are seen (in a random order) before any duplicates. This is what is in the body:
<form name="imageForm">
<table border=3>
<tr align="center">
<td>
<input onclick="displayImage();" type=button value="Click Here">
</td>
</tr>
<tr>
<td>
<img src="blank.jpg" name="canvas" />
</td>
</tr>
</table>
</form>
Here is the script:
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
document.canvas.src = imagesArray[num];
}
</script>
From what I have read, the way to do this would be to add a spice, and have shown images dropped into a new array, then once the original array equals 0, then have it reset. Try as I might, I have not been able to successfully integrate that into my code :( . This is what I ended up with (which does nothing, and breaks the function entirely):
<script>
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var shownImages = []
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
document.canvas.src = imagesArray[num];
shownImages.unshift(imagesArray.splice(num,num+1));
if(images.length == 0){
images.Array = shownImages;
shownImages = [];
return shownImages[0];
}
</script>
Another method mentioned seemed to be to have a function that shuffled the images first, then displayed them in the shuffled order, then reshuffled and repeated, but I got even less far with that.
There also seems to be some question on whether the random number max should be imagesArray.length by itself, or +1 or -1. I am sure there are a number of other issues with this as well, but like I said, this is my first attempt. Any help is appreciated.
You should keep track of the numbers that you have generated, and if its a repeat then get a new number.
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var usedImages = {};
var usedImagesCount = 0;
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
</script>

How to display a variable that changes (like a number) within an html page?

Let's say i have a simple page that just contains a button that when clicked adds 1 to a java script num variable:
HTML:
<body>
<div>
<button type="button" onclick="someFunction()">Clicking here adds 1 to the "count" variable</button>
</div>
<br>
<div id="output"></div>
</body>
Javascript:
var count = new num;
someFunction() {
count =+ 1;
}
So my question is what would you put into the js to display the "count" varible in the div with the id "output"? do you use innerHTML? Because that doesn't seem to work....
Also, is it possible with or without jQuery?
Why not? However, you have to note that number increment must be done with count += 1 or shorter count++. In the following example I have used prefix increment to do the calculation before assignment.
var count = 0;
function someFunction() {
document.getElementById("output").innerHTML = ++count;
}
Additionally, consider initialising numeric variables with its' initial values as described above.

Categories