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

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>

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>

JavaScript Display Image and Text Rather than Alert Message

I'm a newbie and starting to learn coding. I have a question regarding the famous "How many fingers am I holding up?" project. So instead of an alert message, I want the actual image of a finger with 1-5 and the message of either it is correct or not.
I think there are jquery codes.. but i don't want to jump to jquery and learn hardcore javascript first. I'm stuck with creating image Arrays and cannot manage to make the image come up.
Here's the code I have:
<body>
<p>How many fingers am I holding up?</p>
<p><input type="text" id="guess"> <button id="checkGuess">Guess!</button></p>
<div id="image"></div>
<div id="text"></div>
<script type="text/javascript">
var imgArray = new Array();
imgArray[1] = new Image();
imgArray[1].src="images/1.png";
imgArray[2] = new Image();
imgArray[2].src="images/2.png";
imgArray[3] = new Image();
imgArray[3].src="images/3.png";
imgArray[4] = new Image();
imgArray[4].src="images/4.png";
imgArray[5] = new Image();
imgArray[5].src="images/5.png";
document.getElementById("checkGuess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
} else {
alert("Nope! The number was " + randomNumber);
}
}
</script>
</body>
Thanks Guys! Appreciate your help!
Cheers!
Char
I think you can do something like this fiddle.
https://jsfiddle.net/6a4p2po4/5/
What I did was to make the imgArray an array of src of images, and updated the img src depending on the result.
I noticed while working you have some typos and unset variables.
For example, "doument" is misspelled, and "'num'" is not set.
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
It might help to use Chrome or another browser to check the console (F12). It will definitely help you debug.
Using console.log() instead of alert() will make it show up as a log instead of a pop up window, so you can check the values that you stored on variables, i.e. console.log(randomNumber);
You're on the right track! Good job so far!
You said
So instead of an alert message, I want the actual image of a finger...
which leads me to think that we never want to call alert() and instead want to display an image and a message. Assuming I am correct in my supposition, here is some code...
<html>
<head>
<!-- some other stuff... -->
<!-- CSS is your friend! -->
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<p>How many fingers am I holding up?</p>
<p>
<input type="text" id="guess">
<button id="checkGuess" onclick="checkGuess()">Guess!</button>
</p>
<div id="image">
<!-- We can put the images in here then just hide/show them, which is much easier! -->
<img class="hidden" src="./images/1.png"/>
<img class="hidden" src="./images/2.png"/>
<img class="hidden" src="./images/3.png"/>
<img class="hidden" src="./images/4.png"/>
<img class="hidden" src="./images/5.png"/>
</div>
<div id="text"></div>
<script>
function checkGuess(){
var actualFingerCount = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
//the `+` casts the value into a number
var userGuess = +document.getElementById('guess').value;
//get all of our images
var images = document.querySelectorAll('img');
//hide all of them just to be safe
images.forEach(function(img){
img.classList.add('hidden');
});
//then show the one we want
images[actualFingerCount - 1].classList.remove('hidden');
var textDiv = document.getElementById('text');
if(actualFingerCount === userGuess) {
textDiv.innerHTML = 'Yay, you got it!';
}
else {
textDiv.innerHTML = 'Whoops, try again! The number was ' + actualFingerCount + '.';
}
}
</script>
</body>
</html>
And there you have it!
Notice that this is a contrived example. In the real world, you should never define functions in the global namespace, nor should you rely on elements being in a certain order, like I did with the images. Maybe you can take it and improve it to follow better coding standards!

Change picture in an array with button click

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>

How can I save variables on refresh?

<!DOCTYPE HTML>
<html>
<head>
<title>Zautra Levels</title>
<h2 style="font-family: Trebuchet MS; color: blue;"">Zautra Levels</h2>
<p> </p>
</head>
<body>
<p>Clickables:</p>
<button id="swag" onclick="lmao()">Gain XP</button> <button id="gold" onclick="getgold()">Get Gold</button> <button id="buyupgrade" onclick="buyupp()">Level Up!</button>
<p> </p>
<div id="total">XP: 0</div>
<div id="goldt">Gold: 0</div>
<div id="upgradess">Level: 0</div>
<div id="upcostt">Required XP: 25</div>
<script>
var clicks = 0; // How many clicks you have
var upgrades = 0; // How many upgrades you have purchased
var upcost = 25; // How much the upgrades cost
var gold = 0; // How much gold you have
function updateclicks() { // Declares the function that updates the "Zautra Clicks" Text.
var v=document.getElementById("total");
v.innerHTML = 'XP: ' + clicks;
}
function updategold() { // Declares the function that updates the "Zautra Clicks" Text.
var g=document.getElementById("goldt");
g.innerHTML = 'Gold: ' + gold;
}
function updateupgradecounter() { // Declares the function that updates the "Upgrades:" Text.
var y=document.getElementById("upgradess");
y.innerHTML = 'Level: ' + upgrades;
}
function updateupcost() { // Declares the function that updates the "Upgrade Cost:" Text.
var z=document.getElementById("upcostt");
z.innerHTML = 'Required XP:' + upcost;
}
var x=document.getElementById("swag"); function lmao() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
clicks+=1;
updateclicks();
}
var j=document.getElementById("gold"); function getgold() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
gold+=1;
updategold();
}
var c=document.getElementById("buyupgrade"); function buyupp() {
if (clicks >= upcost) {
clicks-=upcost
upgrades+=1
upcost*=2
updateclicks();
updateupgradecounter();
updateupcost();
}
else
{
var clicksdif = upcost - clicks;
confirm("You need " + clicksdif + " more XP to level up.");
}
}
</script>
</body>
</html>
This is the code for my game that I am working on.
I'm trying to add a button, and when you press it, it saves all of the variables.
If you're level 5 with 26 XP, and 7 gold, you refresh the page, you still have those stats instead of losing them on refresh.
Please help!
(And yeah, I do realize that the code is really messed up, but that is a small issue. I'll fix that sooner or later.)
I believe that actually the easiest way, easier than cookies, is to pass the values via the URL. Example:
<form action="yourPage.php?gold=$amount&level=$whatlevel&experience=$experience" method="POST">
//Your refresh button here
</form>
and then to retrieve those variables when the page reloads, use: gold=$_POST['gold']
Another option as well is to use the GET method instead of POST.
Keep in mind that the file extension needs to be php for this code to work.
you could create a cookie in php:
setcookie("NameOfTheCookie",$value,$expireTime)
and $value can be an array of values as well.

Javascript to image cycle

Simple request, but I don't know how to do it. I've got a series of 10 images (image0.gif, image1.gif image2.gif etc...) that need to change to the next image in the sequence (cycling around after 9) when another image is pressed. This is what I have so far...
<html>
<head></head>
<body bgcolor="#808080">
<script type="text/javascript">
var c = 0;
function preload(img) {
var a = new Image();
a.src = img;
return a;
}
if (needed) {
time0 = preload("image0.gif");
time1 = preload("image1.gif");
time2 = preload("image2.gif");
time3 = preload("image3.gif");
time4 = preload("image4.gif");
time5 = preload("image5.gif");
time6 = preload("image6.gif");
time7 = preload("image7.gif");
time8 = preload("image8.gif");
time9 = preload("image9.gif");
}
function clickme() {
// update image
c += 1;
// alert(c)
}
</script>
<div align="center">
<center>
<img src="images/image0.gif" width="20" height="55" name="time0"> <a href="#" onMouseDown="return clickme()">
<img src="images/button.gif" border="0" width="96" height="55">
</a>
</td>
</tr>
</table>
</center>
</div>
</body>
</html>
First, you can and should take advantage of the fact, that only thing diferrent in the each umage name is number. So, you can store number and create any image name:
function getImage(id) {
return "image"+id+".gif";
}
Then, you should have a way to acces the image that you want to change. Like adding id to he element:
<img id="changing" src="image0.png" />
There should be onclick used, not onmousedown. User may change his mind and hower the mouse away - that is not click:
<a href="#" onclick="clickme()" />
Finally, changing the image element:
var c=0;
var max = 9;
function clickme() {
c++;
if(c>max)
c=0; //looping back to zero
docment.getElementById("changing").src = getImage(c); //getImage is defined above
}
Put an id on the image (the-image, for instance).
function clicme() {
c += 1;
document.getElementById('the-image')
.setAttribute('src', 'image' + (c % 10) + '.gif');
}
Also there is no href element. I think you meant to type <a href.

Categories