is it possible to add 3 photos to this code? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
for this task i have to get 3 photos and make a button to cycle through the photos new i need to make it so that i can use photos from my file
.Every little helps :D
<!DOCTYPE html>
<html>
<body>
<img id="light" src="Red.png">
<script>
var list= ['Green.png', 'Yellow.png', 'Red.png'];
var i = 0;
function lightsCycle() {
i = i + 1;
i = i % list.length;
var light = document.getElementById("light").src = list[i];
}
</script>
<button type = "button" onclick="lightsCycle()">Next Light</button>
</body>
</html>
UPDATE: I have modified my code to attempt one of the answers given here, but I am still having trouble:
<!DOCTYPE html>
<html>
<body>
<img id="light" src="Red.png">
<script>
var list= ['https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png',
'https://img.clipartfox.com/837fed127e3383c2a61cf08f76a65081_pics-for-stop-light-yellow-clipart-traffic-light-yellow_641-880.png',
'http://previews.123rf.com/images/blojfo/blojfo1003/blojfo100300021/6559248-Traffic-light-with-red-light-Stock-Photo.jpg'];
var i = 0;
function lightsCycle() {
i = (i < list.length - 1) ? ++i : 0;
document.getElementById("light").src = list[i];
}
</script>
<img id="light" src="https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png">
<button type = "button" onclick="lightsCycle()">Next Light</button>
</body>
</html>

In your function, you are incrementing i and then immediately throwing that value away on the next line where you are setting i to the modulo of i and the length of your array. That line is not needed.
You also need to check to see if i is at the highest index number that the array supports and, if so, reset it to 0.
Next, the line:
var light = document.getElementById("light").src = list[i];
unnecessarily declares a variable called light since you never use it anywhere.
Lastly, don't use HTML attributes to hook up event handlers (onclick, onmouseover, etc.) as they:
create spaghetti code (HTML and JavaScript mixed on the same line) that is difficult to read and maintain.
create globally scoped wrapper functions around your attribute's value that alter the this binding and can cause your function to not work correctly.
don't follow W3C standards for event handling.
// Put the correct relative paths to your images back into the array. Here, I'm substituting
// online images so that you can see the code working properly.
var list= ['https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png',
'https://img.clipartfox.com/837fed127e3383c2a61cf08f76a65081_pics-for-stop-light-yellow-clipart-traffic-light-yellow_641-880.png',
'http://previews.123rf.com/images/blojfo/blojfo1003/blojfo100300021/6559248-Traffic-light-with-red-light-Stock-Photo.jpg'];
var i = 0;
// Only scan the document one time to get a reference to the image element.
// It's a waste of resources to do it every time the button is clicked
var img = document.getElementById("light");
var btn = document.getElementById("btn")
// Don't use HTML attributes to hook up event handlers (onclick, onmouseover, etc.)
btn.addEventListener("click", lightsCycle);
function lightsCycle() {
// If i is less than the max index, increment it, otherwise set it to zero
i = (i < list.length - 1) ? ++i : 0;
// Set the source of the image element to the next array value
img.src = list[i];
}
img { width:50px; }
<img id="light" src="https://cdn2.iconfinder.com/data/icons/crystalproject/crystal_project_256x256/apps/daemons.png">
<button type="button" id="btn">Next Light</button>

Related

Why are the images not coming up for document.createElement

I am a very novice coder and I am creating a game that calculates the area of a given rectangle however once the page loads, the image does not show and thus the user cannot answer the question.
An example image has been copied below
The "score" does not display either. Any help would be greatly appreciated :)
var number1;
var number2;
var response;
var calcanswer;
var score = 0;
window.onload = areaquestion1;
myScore.text = "SCORE: " + score;
function areaquestion1() {
var question = document.createElement("question");
question.setAttribute("src", "Images/2*1.png");
question.setAttribute("width", "304");
question.setAttribute("height", "228");
question.setAttribute("alt", "2*1");
document.body.appendChild(question);
var number1 = 2
var number2 = 1
calcanswer = (number1*number2);
var question = document.getElementById("question");
question.innerHTML = "What is the area of this lego brick?";
check();
areaquestion2();
}
function areaquestion2() {
var question = document.createElement("question");
question.setAttribute("src", "Images/3*2.png");
question.setAttribute("width", "304");
question.setAttribute("height", "228");
question.setAttribute("alt", "3*2");
document.body.appendChild(question);
var number1 = 3
var number2 = 2
calcanswer = (number1*number2);
var question = document.getElementById("question");
question.innerHTML = "What is the area of this lego brick?";
check();
areaquestion3();
}
function check()
{
var statusDiv = document.getElementById("status");
response=document.getElementById("answer").value;
if(response != calcanswer)
statusDiv.innerHTML="Incorrect";
else
if (response==calcanswer)
{
statusDiv.innerHTML="Very good!";
score ++;
document.getElementById("score").textContent = score
document.getElementById("answer").value = "";
problem();
}
}
<!DOCTYPE html>
<html>
<title>Lego Area</title>
<head>
<link rel="stylesheet" href="CSS/Play.css">
<script src="JavaScript/Play.js"></script>
</head>
<body onload="areaquestion1();">
<div class="header">
<h1>LEGO AREA</h1>
<p>Calculating <b>area</b> with Emmet.</p>
<div id="score" class="score" value="SCORE:"></div>
</div>
<form>
<div class="row">
<div class="side">
<div id="question"></div>
<div id ="prompt"></div>
<input type="text" id="answer"/>
</div>
<div class="main">
<input id="solve" type="button" value="CHECK!" onclick="check()" />
</div>
</div>
</form>
<div id="status"></div>
<!-- Footer -->
<div class="footer">
<div class="practice"> <img src="Images/legoBlue2.png" id="practicebtn" width="20%"></div>
<div class="play"> <img src="Images/legored2.png" id="playbtn" width="20%"></div>
</div>
</body>
</html>
This is my first question I'm attempting to answer -- so pretty big deal. Anyway...
A few things I noticed:
I got pretty confused reading the code seeing the question variable being used so much for different parts of the code. So I changed the var question to var imageBlock to make it more readable for me.
You were running the areaquestion1() function onload. Since the check() function was run as a part of the areaquestion1() function it was being run as well, in-turn displaying 'Incorrect' even before an answer was entered. I changed this to document.getElementById("solve").check(); to ensure it runs only after the CHECK! button was clicked.
Finally getting to your actual question. It looks like you are trying to use document.createElement to create an image with an id of question, however based on geeks for geeks and W3 Schools you use the document.createElement to create the img element. THEN you can set the id attribute to whatever you like. In this case, I switched it to imageBlock.setAttribute("id", "madeUpImg"); to help with my readability.
So this is what I did, I think there are a lot of improvements you can make, but this works and it will give you a good start:
function areaquestion1() {
var imageBlock = document.createElement("IMG");
imageBlock.setAttribute("id", "madeUpImg");
imageBlock.setAttribute("src", "guWFE.png");
imageBlock.setAttribute("width", "304");
imageBlock.setAttribute("height", "228");
imageBlock.setAttribute("alt", "2*1");
document.body.appendChild(imageBlock); // this appends it to the bottom of the page
number1 = 2
number2 = 1
calcanswer = (number1*number2);
var question = document.getElementById("question");
question.innerHTML = "What is the area of this lego brick?";
document.getElementById("solve").check();
// areaquestion2(); }
All of this is edited to address your further questions:
For appending it in the appropriate spot: I haven't had time to jump back in my code, but this is what I'm thinking. Currently, when you read your code you have document.body.appendChild(question); This JavaScript is telling the computer to find the document, then find the body of that document, then run the appendChild function. So, basically it is saying - "computer, append the question variable to the body of the document". So, what's wrong with this? Well, you want to append it to a specific div! So, you're extremely close, but you're not grabbing the question div! You need to use code to tell the computer to find the question div, then append the image to that div. I'd do something like this: document.getElementById('question').appendChild(imageBlock) this now means the code is grabbing onto the div that you want to append it to then, appending the imageBlock to that div.
I commented out that areaquestion2 because I know you're going to run into more problems. 1. If you call the areaquestion2in the areaquestion1 function it will run immediately when the website loads (you're calling the area question1 on load). I think this is going to make both images appear at the same time. Why? It is just being instructed to append another image to the question div. 2. You probably don't want both images appearing at the same time. So, you're going to need to find a way to replace the first image rather then trying to add another one.
That's about all I can help you with on this for now. I think that if you continue to work through this then refactor it, you're going to learn a ton. I think you should try to bring this to one function by assigning questions to variables, then passing those variables in as arguments to your function. If you haven't already, I'd highly recommend going through FreeCodeCamp's stuff lesson by lesson.
Hope this helped!!

Program doesn't work and I don't know why [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am making a script that is supposed to display a button and a coloured circle on a webpage. When this button is pressed, it is supposed to change the colour of the circle. There are 3 colours which are supposed to be looped through so they should change, in order, every time I press the button.
The issue is, when i run my code, it simply displays the coloured circle I chose when making the tag and doesn't change when I press the button.
Here's my code:
<!doctype html>
<html>
<head>
<title>Traffic Lights</title>
</head>
<body>
<img id="trafficimg" src="green.jpg" alt="Change Now!">
<button type="button" onClick="changelight()"> Change the Lights! </button>
<script>
var assets = ["red.jpg","yellow.jpg","green.jpg"]
var state = 1
var colour = ""
function changelight() {
if state == 1{
var colour = "green";
if state == 2{
var colour = "orange";
if state == 3{
var colour = "red";
}
if colour.includes("green"){
document.getElementById("trafficimg").setAttribute('src', assets[0]);
state=state+1;
if colour.includes("green"){
document.getElementById("trafficimg").setAttribute('src', assets[1]);
state=state+1;
if colour.includes("green"){
document.getElementById("trafficimg").setAttribute('src', assets[2]);
state=state - 2;
}
}
}
</script>
</body>
</html>
I would be helpful to get simple solutions that don't change the code too much if possible, though, any help is much appreciated. Thank you all.
You need to wrap the conditions in parenthesis
if (state == 1) {
// ^ ^
colour = "green";
// no need to redeclare color
}
// missing curly bracket at the end of if statement
Working example with state as index for the image array.
var assets = ["https://dummyimage.com/50x50/F00/000000&text=+", "https://dummyimage.com/50x50/FF0/000000&text=+", "https://dummyimage.com/50x50/0F0/000000&text=+"],
state = 0;
function changelight() {
state++; // increment state
state %= assets.length; // remainder operator for keeping state in range of array
document.getElementById("trafficimg").setAttribute('src', assets[state]);
}
<img id="trafficimg" src="https://dummyimage.com/50x50/F00/000000&text=+" alt="Change Now!"><br>
<button type="button" onClick="changelight()"> Change the Lights! </button>
Hi there are multiple errors (actually numerous) errors in your short snippet. BTW, I think you wanted to make this:
var state = 1;
var colour = "green";
function changelight(state) {
if (state == 1){color = "green";}
if (state == 2){color = "orange";}
if (state == 3){color = "red";}
switch(color){
case 'green': {document.getElementById("para1").style.background = 'green'; break;}
case 'orange': {document.getElementById("para1").style.background = 'orange'; break;}
case 'red':{document.getElementById("para1").style.background = 'red'; break;}
}
}
<p id="para1" style="background:green;width:50px;height:50px;border-radius:50%;"></p>
<button type="button" onClick="changelight(1)"> green</button>
<button type="button" onClick="changelight(2)"> orange</button>
<button type="button" onClick="changelight(3)"> red</button>

How do I get this traffic Light sequence to work with the click of the button???

So, I can get it to go from red to amber, but I am stuck on how to further get it to change to green, back to amber and then red again. Any help would be highly appreciated.
Also, I have created this on dreamwaver.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Traffic Lights </h1>
<img id="light" img src="../../red.jpg">
<button type="button" onClick="changeLights()">Change Lights</button>
<script>
function changeLights(){
document.getElementById('light').setAttribute("src","../../amber.jpg")
document.getElementById('light').setAttribute("src","../../green.jpg")
document.getElementById('light').setAttribute("src","../../amber.jpg")
//document.getElementById('light').setAttribute("src","../../red.jpg")
}
</script>
</body>
</html>
The best solution is to put the image names into an array and the cycle through the array using a counter. That counter can increase or decrease the count depending on which "end" of the array we've last hit.
Also, don't use inline HTML event handling attributes (onclick, etc.) as they create "spaghetti code", they cause global wrapper functions that alter the this binding and they don't follow the W3C Event Model standard. Instead wire elements them up to event handlers via code using .addEventListener().
// Get references to DOM elements:
var img = document.getElementById('light');
var btn = document.getElementById('btn');
// Hook click of button up to event handling function
btn.addEventListener("click", changeLights);
// Put image names into an array:
var imgs = ["green.jpg" , "amber.jpg", "red.jpg"];
// Establish counter variable and directional variable
var count = 0;
var additive = 1;
function changeLights(){
// Set image by getting element from array based on current counter value
img.setAttribute("src","../../" + imgs[count]);
// Verification of action
console.clear();
console.log(img);
// When we hit the edges, reverse direction,
if(count === 2) {
additive = -1; // Go backward
} else if(count === 0) {
additive = 1; // Go forward
}
// Adjust the count accordingly
count+= additive;
}
<h1>Traffic Lights </h1>
<img id="light" img src="../../red.jpg">
<button type="button" id='btn'>Change Lights</button>

JavaScript, image changing program not functioning

So I'm new to coding, so thought that I would give some more simple things a go. I tried to make a code which would change an image every time a button is pressed, but it does not function. For a while I had it functioning so that the square would display but the image would not change when the button is pressed. But I then altered it and it will now not run with internet explorer due to a syntax error. Any help would be seriously appreciated, please bare in mind that it could be completely wrong, as I just used guides off of the internet :) I also probably inserted this code wrong, but I tried ;)
<!DOCTYPE html>
<html>
<body>
<img id="shape" src="square.gif">
<button type="button" onclick="changeImage()">Change Image/button>
<script>
var list = [
"red.gif",
"square.gif"
];
var index = 0;
function changeImage() {
index = index + 1;
if (index == list.length) index = 0;
var image = document.getElementById('shape');
image.src=list[index];
}
</script>
I did find two things that will help your code work better:
I fixed your closing button tag
I iterated your index variable after the if statement and image replacement. That way your first click didn't use the same image.
This tested fine in IE with no errors.
See my code below.
var list = [
"http://placekitten.com.s3.amazonaws.com/homepage-samples/96/140.jpg",
"http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg"
];
var index = 0;
function changeImage() {
var image = document.getElementById('shape');
if (index == list.length) index = 0;
image.src=list[index];
index = index + 1;
}
<img id="shape" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg" />
<button type="button" onclick="changeImage()">Change Image</button>

JavaScript Timed Image Swap Need Help

So in my script I have...
<script type="text/javascript">
var images = new Array();
var numImages = 3;
var index = 0;
function setupSwapper() {
for (i = 0; i < numImages; i++) {
images[i] = new Image(266, 217);
images[i].src = "images/image" + i + ".png";
}
setTimeout("swapImage()", 5000);
}
function swapImage() {
if (index >= numImages) {
index = 0;
}
document.getElementById('myImage').src = images[index].src
index++;
setTimeout("swapImage()", 5000);
}
</script>
And then I have <body onload="setupSwapper()"> to setup the body.
and <img width=266 height=217 id="myImage" name="myImage" src="images/image0.png"></img> elsewhere in my document.
Only the initial image (image0.png) is showing up. I'm probably blind from having looked at this so long. The images are not swapping.
Use FireBug or a similar tool for debugging what's going on:
Does the img DOM element in fact gets its src changed ?
Do you see any network activity trying to load the images ? does it succeed ?
Set up breakpoints in your code and see what happens in the debugger
BTW - You can use setInterval instead of setTimeout - it sets a repeating timer
You're missing the () in the definition of "setupSwapper".
Also it's setTimeout, not setTimeOut.
Finally, get rid of the "type" attribute on your <script> tag.
You might want to start "index" at 1 instead of 0.
The way to go:
setTimeout(swapImage, 5000);
[FORGET] the type attribute has nothing to do with it
[FORGET] the index has nothing to do with it
[OPTIONAL] remove "name" attribute from the image (useless)
[OPTIONAL] close image tags like <img />
Note: 2-5 is about correctness. Only the first one is important to get it work.
Get Firebug, use it's debugger to put breakpoints inside swapImage to see if it is hit after the timeout. Another way is to use the console.* apis to see what's happening(e.g. console.log).

Categories