javascript and html traffic light not working [closed] - javascript

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>

Related

How to repeat the same image a number of times in html? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 4 years ago.
Improve this question
I want to repeat an image-"box1" throughout the width of the page. I tried the following but it isn't working.
var count = $(window).width() / $("#box1").width();
for (var i = 1; i <= count; i++) {
var paragraph = document.getElementById("top-section");
paragraph.innerHTML += "<img src='images/box1.png' id='box1'html>";
}
#top-section {
float: left;
}
<div id="top-section"></div>
This one works fine for me.
Check it out...
Just clone element what u need and append it inside the section.
var count = $(window).width() / $(".box1").last().width();
for (var i = 1; i <= count; i++) {
$("#top-section").append($(".box1").last().clone(true));
}
#top-section {
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="top-section">
<img src="images/box1.png" class="box1">
</div>

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>

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>

Simple Javascript Program Not Working [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 8 years ago.
Improve this question
So I'm new to JavaScript and I just wrote a simple program; however, I'm not sure why it isn't working. I have shown both the HTML and the Javascript code below.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Rectangular Prism Calculator</h1>
<h2 id="hLength">Length: N/A</h2>
<h2 id="hWidth">Width: N/A</h2>
<h2 id="hDepth">Depth: N/A</h2>
<h2 id="hSurfaceArea">Surface Area: N/A</h2>
<h2 id="hVolume">Volume: N/A</h2>
<script src="main.js"></script>
</body>
</html>
JavaScript:
var length;
var width;
var depth;
length = 20;
width = 10;
depth = 15;
// Write length to document
var wLength = document.getElementbyId('hLength');
wLength.textContent = "Length: " + length;
// Write width to document
var wWidth = document.getElementbyId('hWidth');
wWidth.textContent = "Width: " + width;
// Write depth to document
var wDepth = document.getElementbyId('hDepth');
wDepth.textContent = "Depth: " + depth;
// Calculate surface area
var calculateSurfaceArea = function(l, w, d) {
var surfaceArea = 2*l*d + 2*l*w + 2*w*d;
return surfaceArea;
}
// Write surface area to document
var wSurfaceArea = document.getElementById('hSurfaceArea');
wSurfaceArea.textContent = "Surface Area: " + calculateSurfaceArea(length, width, depth);
// Calculate volume
var calculateVolume = function(l, w, d) {
var volume = l*w*d;
return volume;
}
// Write volume to document
var wVolume = document.getElementById('hVolume');
wVolume.textContent = "Volume: " + calculateVolume(length, width, depth);
Just to verify, I have made sure that the name of the HTML document is 'index.html' and the JavaScript document is named 'main.js'
Many Thanks,
Malleekk
You have a typo in your code:
getElementbyId
should be:
getElementById
Working Demo of your corrected code
You should learn how to debug your Javascript code. Get along with Firebug in Firefox / Developer Tools in Chrome.
Javascript is case sensitive and usually the names of functions has camel case style, so this is wrong:
... document.getElementbyId ...
Replace with
... document.getElementById ...

How to change css class for multiple DOM elements with jQuery? [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 8 years ago.
Improve this question
I am trying to change class property of an DOM element (specifically, for label tag) using jQuery 1.10.2.
Here is my code:
var MyNameSpace = MyNameSpace || {};
MyNameSpace.enableDisableLabels = (function() {
var m_labelIds = {
"bookId": "book",
"customerId": "customer"
};
var mf_getjQueryDOMObjectReperesentation = function(arrayObjIds) {
var result = {};
$.each(arrayObjIds, function(id, value) {
result[id] = $("#" + value);
});
return result;
};
var mf_unBoldLabels = function(arrayjQueryObjLabels) {
$.each(arrayjQueryObjLabels, function(id, value) {
value.atrr("class", "outputLabelOpt"); // PROBLEM: TypeError: value.atrr is not a function
});
};
var arrayjQueryObjLabels = mf_getjQueryDOMObjectReperesentation(m_labelIds);
mf_unBoldLabels(arrayjQueryObjLabels);
}());
.outputLabelOpt {
color: #0B63CA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>
<label id="book" style="font-weight:bold">book</label>
<label id="customer" style="font-weight:bold">customer</label>
</body>
But I get an error:
TypeError: value.atrr is not a function
Can you please advise what am I doing wrong and how to do it correctly.
Any kind of help is very much appreciated.
Thank you in advance,
mismas
Just a typo : it is not atrr, but attr ;-)
This is value.attr not .atrr.
For class attribute manipulation, you also have .addClass("classname") and .removeClass("classname").

Categories