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

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>

Related

JavaScript Background Color Toggle [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 3 years ago.
Improve this question
I have this simple function that is just simply supposed to toggle the background color of a button from aqua to red and back again. However, when I call this function, all it does is change it to red and I'm not sure why. I have looked at other similar examples on here and I feel like I'm doing it correctly. Would love some help!
<button id = "button1" onclick="myFunction()">This is a button</button>
button {
background-color: Aqua;
}
function myFunction() {
if (document.getElementById("button1").style.backgroundColor === "Aqua"){
document.getElementById("button1").style.backgroundColor = "Red";
document.getElementById("button1").innerHTML = "I'm RED!!";
} else {
document.getElementById("button1").style.backgroundColor = "Aqua";
document.getElementById("button1").innerHTML = "I'm back BABY!!";
}
}
it works like this
if ($("#yourselector").css('background-color')=="rgb(220,
20, 60)") alert("matched");
you need to convert name to red, green, blue components, you might use this tool
http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
The simplest wya to do this is to pass this into your onclick() function and use a ternary operator to determine the toggle state.
function myFunction(btn) {
const isRed = btn.style.backgroundColor === "red";
btn.style.backgroundColor = isRed ? "aqua" : "red";
btn.innerHTML = isRed ? "I'm back BABY!!" : "I'm RED!!";
}
button {
background-color: aqua;
}
<button id="button1" onclick="myFunction(this)">This is a button</button>
the first if statement should have lowercase aqua.. like the following
function myFunction() {
if (document.getElementById("button1").style.backgroundColor === "aqua") {
document.getElementById("button1").style.backgroundColor = "red";
document.getElementById("button1").innerHTML = "I'm RED!!";
} else {
document.getElementById("button1").style.backgroundColor = "aqua";
document.getElementById("button1").innerHTML = "I'm back BABY!!";
}
}
I found out by doing
console.log(document.getElementById("button1").style); and in the log you will have the object where you can unfold and find that the css selector is in lowercase,
also make red the same to avoid confusion.
hope it helps

How to display grade as an alert in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have been trying to get this code to work, my assignment is to create a javascript where the user inputs a letter grade then it gives them an alert of what kind of grade they are gonna get. For some odd reason, I cant get the alert working. My teachers example involves using a function but I dont know what to put in there.
<html>
<head>
<script>
Function(){
var x = document.getElementById("score").value;
if x >=1: {
alert("invalid grade")
}
if .99>= x >=.9: {
alert("A");
}
if .89>=x>=.8:{
alert("B");
}
if .79>=x >=.7:{
alert("C");
}
if .69>=x >=.6:Z{
alert("D");
}
if x<=.59:{
alert("F");
}
{
</script>
</head>
<body>
<p>Enter Score in the box:</p>
<input type="text" id="score">
<button onclick=print("x")">click</button
<body>
</html>
See all the comments below:
<html>
<head>
</head>
<body>
<p>Enter Score in the box:</p>
<input type="text" id="score">
<button>click</button>
<!-- Your script should be just before the closing body tag
so that by the time the browser reaches it, all the HTML
will have been read into memory. Your teacher isn't really
showing you the most correct technique if he/she told you
to put it in the HEAD section. -->
<script>
// Set up event handling in JavaScript, not in HTML. Your teacher is wrong
// to teach you that way. First, find the right HTML element, then configure
// it for the event and the function to call when the event occurs.
document.querySelector("button").addEventListener("click", showGrade);
// JavaScript is case-sensitive. Functions use the word "function" (lower case)
// and, in this case, need a name (that you can make up) to be able to call it later.
function showGrade(){
var x = document.getElementById("score").value;
// The condition for an "if" must be in parenthesis
// and when there are multiple parts to the conditon
// you have to use AND (&&) or OR (||) operators and
// each part must be a complete condition on its own.
// Also, the colons you had were incorrect syntax.
// Lastly, because a grade will be only one of your
// choices, you should use "else if" on the second and
// subsequent tests, so that if the first test fails,
// each of the next ones will run. But, once you've
// ruled out all the possiblilites except for one (the
// last one), you don't need to test and just use "else".
// For example, if the grade isn't and A,B,C, or D, it
// must be an F.
if (x >=1 ){
alert("invalid grade")
} else if (x >= .9 && x <= .99) {
alert("A");
} else if (x >= .8 && x <= .89) {
alert("B");
} else if (x >= .7 && x <=.79) {
alert("C");
} else if (x >= .6 && x <= .69) {
alert("D");
} else {
alert("F");
}
}
</script>
</body>
</html>
More reading:
Using .addEventListener() to set up event handlers
Finding elements in the document with .querySelector()
Writing an if...else/if statement

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

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>

javascript and html traffic light not working [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
So the red traffic light shows up and then when the next light button is pressed the light doesn't change and I can't for the life of me figure out why. I would appreciate any help. Here's the code:
<!DOCTYPE html>
<html>
<body>
<img id="thestartlight" src="file:\\\C:\Users\Sony\Desktop\Amul's USB\IT\it test\traffic-light-red.jpg">
<button type="button" onclick="nextLightClick()">Next Light</button>
<script>
var list = [
"file:\\\C:\Users\Sony\Desktop\Amul's USB\IT\it test\traffic-light-red.jpg.html"
"file:\\\C:\Users\Sony\Desktop\Amul's USB\IT\it test\traffic-light-amber.jpg",
"file:\\\C:\Users\Sony\Desktop\Amul's USB\IT\it test\traffic-light-green.jpg",
"file:\\\C:\Users\Sony\Desktop\Amul's USB\IT\it test\traffic-light-red.jpg"
];
var index = 0;
var lightsLen = lights.length;
function nextLightClick() {
index++;
if (index == lightsLen)
index = 0;
var image = document.getElementById('thestartlight');
image.src = lights[index];
}
</script>
</body>
</html>
There are 3 problems.
1) it's list have to be lights
2) better put images to images/lights/ folder in relative to Your code folder.
3) html file cannot be shown in image tag
Here is the fix:
var lights = [
"images/lights/amber.jpg",
"images/lights/green.jpg",
"images/lights/red.jpg"
];
var index = 0;
var lightsLen = lights.length;
It's a typo..
var list = [ ...
should be
var lights [ ...
You named your array list, but you are seeking the images from lights.
You also need to remove the .html file from the array.
var image = document.getElementById('thestartlight');
var lights = [
"http://archive.nassaucountyny.gov/agencies/TPVA/Images/RedLight-2_145x193.jpg",
"http://www.clker.com/cliparts/2/1/1/6/N/W/amber-traffic-light.svg",
"http://www.clker.com/cliparts/6/e/9/d/11949849761176136192traffic_light_green_dan__01.svg"
];
var index = 0;
var lightsLen = lights.length;
function nextLightClick() {
index++;
if (index == lightsLen){
index = 0;
}
image.src = lights[index];
}
img {width:50px;}
<img id="thestartlight" src="http://archive.nassaucountyny.gov/agencies/TPVA/Images/RedLight-2_145x193.jpg">
<button type="button" onclick="nextLightClick()">Next Light</button>

JavaScript "example" of a switch to compare HTML button id's

I posted a question a week ago about how to use JavaScript switch statement to compare this.id. I found it hard to get my function/object methods out of the switch as variables. Using strict mode and trying to do this seems impossible. However I did find one way to get the results I wanted.
"use strict"
function fragmentLoader() {
getID(this.id);
}
function getID(x) {
var theID = x;
switch (theID) {
case "myFirstID":
myDate();
break;
case "mySecondID":
changeStyle();
break;
case "myThirdID":
myText();
break;
default:
otpt = "ERROR!";
}
}
function myDate() {
document.getElementById('content').innerHTML = Date();
}
function changeStyle() {
var whatColor = document.getElementById("content").style.color;
if ( whatColor === "black") {
document.getElementById("content").style.color = "blue";
} else {
document.getElementById("content").style.color = "black";
}
}
function myText() {
document.getElementById('content').innerHTML = "This Text will display";
}
document.getElementById("content").style.color = "black";
document.querySelector('#myFirstID').addEventListener('click', fragmentLoader);
document.querySelector('#mySecondID').addEventListener('click', fragmentLoader);
document.querySelector('#myThirdID').addEventListener('click', fragmentLoader);
<div>
<div>
<button id="myFirstID">
Press for Date and Time.
</button>
</div>
<div>
<button id="mySecondID">
Press to change style color.
</button>
</div>
<div>
<button id="myThirdID">
Press for Text.
</button>
</div>
<p id="content">content here
</p>
</div>
Had to laugh at my example because for some odd reason it takes 2 clicks to get the style to change. Any ideas as to why? NOTE : " This is now FIXED"
Other than that I hope this helps someone else.
-Rob
This line is the reason your code does not work as expected:
document.getElementById("content").style.color === "black";
You're trying to initially set the color to black, but you used to many "=" signs. Change that line to:
document.getElementById("content").style.color = "black";
... and your code will work!

Categories