I am hoping to get help with my IF statement in javascript. What is happening is that its not changing colour when the button is clicked.
This is what i am trying to do. When the next button is clicked, the following should happen
If the background colour of the light div is #ff0000 (red), it should change to #ffff00 (amber)
If the background colour of the light div is #ffff00 (amber), it should change to #00ff00 (green)
If the background colour of the light div is #00ff00 (green), it should change to #ff0000 (red)
HTML:
<div class="main">
<h1>Traffic Light</h1>
<div class="light">
</div>
</br>
<button id="next" onClick="setBgColour" type="button">Next</button>
</div>
css:
.light
{
background-color: #ff0000;
width: 100px;
height: 20px;
margin-left: auto;
margin-right: auto;
}
JavaScipt:
function setBgColour(){
if(document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000')
{
document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00';
}
else if (document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00')
{
document.getElementsByClassName("light")[0].style.backgroundColor = '#00ff00';
}
else
document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000';
}
window.onload = function(){
document.getElementById('next').addEventListener('click', setBgColour);
};
You can simplify this a lot:
var lightnumber = 0; // this variable saves the current state of the traffic light
var lights = [
"#ff0000", "#ffff00", "#00ff00"
]; // this variable saves all possible lights.
setBgColour = function() {
// at first we decide which colour shall be next, so we increase
// the lightnumber by one, except, if we are already at green, then we start over at 0
lightnumber = lightnumber == (lights.length - 1) ? 0 : lightnumber + 1;
// and here we set the light according to our lightnumber variable
document.getElementsByClassName("light")[0].style.backgroundColor = lights[lightnumber];
}
.light {
background-color: #ff0000;
width: 100px;
height: 20px;
margin-left: auto;
margin-right: auto;
}
<h1>Traffic Light</h1>
<div class="light"></div>
</br>
<button id="next" onClick="setBgColour()" type="button">Next</button>
</div>
Your javascript code should be like this:-
function setBgColour() {
if (document.getElementsByClassName("light")[0].style.backgroundColor == '#ff0000') {
document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00';
} else if (document.getElementsByClassName("light")[0].style.backgroundColor == '#ffff00') {
document.getElementsByClassName("light")[0].style.backgroundColor = '#00ff00';
} else {
document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000';
}
window.onload = function () {
document.getElementById('next').addEventListener('click', setBgColour);
};
}
i.e. inside if you need to use ==, not = which is an assignment operator.
Related
Hi I am trying to make a traffic light using an array of pictures.
I currently need to change the image path stated in css when a button is clicked so that the light's picture changes.
So in this case the content.url() line of each class needs to be change when function is called by the button. The method I'm currently using is incorrect but I think it may help to help you understand.
<style>
#rect{
height:550px;
width:180px;
border:1px solid #000;
}
.black1 {
position: relative;
top: 10px;
left: 10px;
content.url('black.png')
}
.black2 {
position: relative;
top: 20px;
left: 10px;
content.url('black.png')
}
.black3 {
position: relative;
top: 30px;
left: 10px;
content.url('black.png')
}
</style>
<Body>
<div id="rect">
<img class="black1" />
<img class="black2" />
<img class="black3" />
</div>
<script>
var x = ["black.png", "red.png", "orange.png",'green.png'];
var i = -1;
function change(){
i++;
if (i == 0){
document.getElementByClass('black1').src=x[1];
document.getElementByClass('black2').src=x[0];
document.getElementByClass('black3').src=x[0];
}
}
</script>
<button onclick = "change()">Change light</button>
</div>
</Body>
</html>
I would separate your css classes in red, orange/yellow, green. Then you can work with the classList function. Bellow you will find a simple working example. Feel free to improve it.
let i = -1;
function change() {
const tl = document.querySelectorAll('.light');
i++;
if (i == 0) {
tl[0].classList.add('red')
}
if (i == 1) {
tl[1].classList.add('yellow')
}
if (i == 2) {
tl[2].classList.add('green')
}
if (i == 3) {
tl[2].classList.remove('green');
tl[1].classList.remove('yellow');
tl[0].classList.remove('red');
i = -1;
}
}
#rect{
height:350px;
width:120px;
border:1px solid #000;
}
img {
height: 100px;
}
.light {
position: relative;
top: 10px;
left: 10px;
content: url(https://via.placeholder.com/150/000000);
}
.red {
content: url(https://via.placeholder.com/150/FF0000);
}
.yellow {
content: url(https://via.placeholder.com/150/FFFF00);
}
.green {
content: url(https://via.placeholder.com/150/008000);
}
<Body>
<div id="rect">
<img class="light" />
<img class="light" />
<img class="light" />
</div>
<script>
</script>
<button onclick = "change()">Change light</button>
</div>
</Body>
</html>
To make your program work, I would make it look something like this:
Get rid of content.url('black.png') in css
Set default urls to your img tags that would be "black.png"
Make working code:
const urls = ["black.png", "red.png", "orange.png",'green.png'];
let index = -1;
const imgs = ["black1", "black1", "black1"].map(className => document.getElementByClass(className));
function change(){
index++;
// will take rest of division,
// for example 4 % 3 === 1, 5 % 3 === 2, 6 % 3 === 0
const currentLight = index % 3;
imgs.forEach((image, i) => {
if (i === currentLight) {
// current image should be active and we map it correct light urls
// for example currentLight is 0, if will make it url[0] which is red
image.src = urls[currentLight + 1];
}
else {
// turn off the lights that are not equal to currentLight
image.src = urls[0];
}
});
}
change(); // initial call to turn the red light on. If not called all lights will be off
Hope this is the behaviour that you were looking for.
But I wrote that you need to get rid of content: url and your question is about changing it. Basically JavaScript cannot modify classes (unless you dynamically generate them with JS from string, but this is a terrible idea). If you really want to use content: url(does not mean you should), you need to create 3 classes .red, .orange and .green with respective urls and toggle those classes with JS like you would do with toggling src's.
I just started learning JavaScript and right now, I'm making a virtual traffic light that lights up red, green and orange. I would like to make a loop by adding a setInterval to the outside. Is this possible or should i use some other method of making a loop. I tried making a a for(;;){} but this causes an error and the webpage never loads. Here is my current code.
var red = document.getElementById("circleRed");
var orange = document.getElementById('circleOrange')
var green = document.getElementById('circleGreens');
setInterval(
setTimeout( function(){
red.style.backgroundColor = "red";
}, 2000),
setTimeout(function(){
green.style.backgroundColor = "green";
red.style.backgroundColor = "black";
}, 5000),
setTimeout(function(){
orange.style.backgroundColor = "orange";
green.style.backgroundColor = "black";
}, 10000),
5000);
#circleRed, #circleGreens, #circleOrange {
width: 50px;
height: 50px;
-webkit-border-radius: 25px;
-moz-border-radius: 25px;
border-radius: 25px;
margin-bottom: 10px;
background-color: "black";
}
.back {
width: 60px;
margin: 10px 0px 10px 20px;
padding-left: 10px;
padding-top: 10px;
padding-bottom: 10px;
background-color: black;
}
body{
margin: 0;
}
<div class="back">
<div id="circleRed">
</div>
<div id="circleOrange">
</div>
<div id="circleGreens">
</div>
</div>
You can cal your all setTimeout function in a loop function. And call this loop function with setInterval.
Note : I also changed some of the color changing sections in your code .
jsfiddle link : https://jsfiddle.net/zgdx5xan/
var red = document.getElementById("circleRed");
var orange = document.getElementById('circleOrange')
var green = document.getElementById('circleGreens');
loop();
setInterval(loop,11000);
function loop(){
console.log("loop started")
setTimeout( function(){
red.style.backgroundColor = "red";
orange.style.backgroundColor = "black";
green.style.backgroundColor = "black";
console.log("red opened")
}, 2000);
setTimeout(function(){
green.style.backgroundColor = "green";
red.style.backgroundColor = "black";
console.log("green opened")
}, 5000);
setTimeout(function(){
orange.style.backgroundColor = "orange";
green.style.backgroundColor = "black";
red.style.backgroundColor = "black";
console.log("orange opened")
}, 10000);
}
#circleRed, #circleGreens, #circleOrange {
width: 50px;
height: 50px;
-webkit-border-radius: 25px;
-moz-border-radius: 25px;
border-radius: 25px;
margin-bottom: 10px;
background-color: "black";
}
.back{
width: 60px;
margin: 10px 0px 10px 20px;
padding-left: 10px;
padding-top: 10px;
padding-bottom: 10px;
background-color: black;
}
body{
margin: 0;
}
<div class="back">
<div id="circleRed">
</div>
<div id="circleOrange">
</div>
<div id="circleGreens">
</div>
</div>
setInterval, like setTimeout also requires a function to be passed as a first argument, in that function you would then be able to compose your setTimeout's.
var red = document.getElementById("circleRed");
var orange = document.getElementById('circleOrange');
var green = document.getElementById('circleGreens');
setInterval(function () {
red.style.backgroundColor = "black";
orange.style.backgroundColor = "black";
green.style.backgroundColor = "black";
setTimeout(function () {
red.style.backgroundColor = "red";
}, 2000);
setTimeout(function () {
green.style.backgroundColor = "green";
red.style.backgroundColor = "black";
}, 5000);
setTimeout(function () {
orange.style.backgroundColor = "orange";
green.style.backgroundColor = "black";
}, 8000);
}, 10000)
I have adjusted your timings a little as your final timeout was longer than the interval. You can see this working here: codepen example
Think to the traffic lights as an object with 3 states, redOn, greenOn and OrangeOn. You need to loop through states, so starting from redOn pass the next one in the sequence and reset in the last one. I think setInterval here is not required as it cause you to care about the total time that's irrelevant.
var red = document.getElementById("circleRed");
var orange = document.getElementById('circleOrange')
var green = document.getElementById('circleGreens');
var redFor = 200 //2000
var greenFor = 500 //5000
var orangeFor = 1000 //10000
let redOn = function(next) {
red.style.backgroundColor = "red";
orange.style.backgroundColor = "black";
setTimeout(next, redFor);
}
let orangeOn = function(next) {
orange.style.backgroundColor = "orange";
green.style.backgroundColor = "black";
setTimeout(next, orangeFor);
}
let greenOn = function(next) {
green.style.backgroundColor = "green";
red.style.backgroundColor = "black";
setTimeout(next, greenFor);
}
let start = function() {
redOn(function() {
greenOn(function() {
orangeOn(start)
})
})
}
start()
#circleRed,
#circleGreens,
#circleOrange {
width: 50px;
height: 50px;
-webkit-border-radius: 25px;
-moz-border-radius: 25px;
border-radius: 25px;
margin-bottom: 10px;
background-color: "black";
}
.back {
width: 60px;
margin: 10px 0px 10px 20px;
padding-left: 10px;
padding-top: 10px;
padding-bottom: 10px;
background-color: black;
}
body {
margin: 0;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="object2.css">
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="back">
<div id="circleRed"></div>
<div id="circleOrange"></div>
<div id="circleGreens"></div>
</div>
<script src="objects1.js"></script>
</body>
</html>
Here's an alternative implementation with equal times for every light.
var red = document.getElementById('circleRed');
var orange = document.getElementById('circleOrange');
var green = document.getElementById('circleGreens');
/* Set an array with the desired order to turn on lights */
var lights = [red, green, orange];
function open(light) {
light.classList.add('opened');
}
function close(light) {
light.classList.remove('opened');
}
function change() {
close(lights[i]);
i = (i + 1) % lights.length;
open(lights[i]);
}
/* Start */
var i = 0;
open(lights[i]);
setInterval(change, 1000);
.circle {
width: 50px;
height: 50px;
border-radius: 25px;
margin: 5px;
opacity: 0.2;
transition: opacity 200ms;
}
.circle.opened {
opacity: 1;
}
#circleRed {
background-color: red;
}
#circleOrange {
background-color: orange;
}
#circleGreens {
background-color: green;
}
.back {
width: 60px;
padding: 5px;
background-color: black;
}
<div class="back">
<div id="circleRed" class="circle"></div>
<div id="circleOrange" class="circle"></div>
<div id="circleGreens" class="circle"></div>
</div>
Explanation:
Instead of changing the background color of every circle from black to its own color to light up the circle or viceversa to switch off, in my example all circles have their respective color (red, green or orange) faded to (almost) transparent with opacity: 0.2 (originally I used 0, but I think it looks better with 0.2) See: opacity.
So, all elements with class .circle have:
.circle {
/* Other properties */
opacity: 0.2;
}
Then, I use a class called opened to turn the opacity to 1 making the circle visible.
.circle.opened {
opacity: 1;
}
Since .circle.opened has higher specificity than just .circle, opacity: 1 prevails on those elements having both classes (circle and opened).
To add or remove the class opened from a light item I use two simple functions open and close that manipulate the element's classList. This is important. In general it's more recommended to define element's properties (styles) in classes and use JS to add or remove this classes to alter the element that to modify element's styles directly with JS.
So, it's cleaner and more recommended to do:
/* CSS */
.red { background-color: red }
/* Javascript */
var element = document.getElementById('#element_ID');
element.classList.add('red');
than:
/* Javascript */
var element = document.getElementById('#element_ID');
element.style.backgroundColor = 'red';
Even though it may seem easier this second way.
To change the lights, I made an array with the elements in the desired order:
var lights = [red, green, orange];
As you can see, every element of the lights Array is one of the circles, we already stored in variables with document.getElementById() (if you're not familiar with arrays, dedicate some time to read and understand what they are and how they work. They're one of the most basic data structures in any programming language, so it's important to master them.)
To start, I initiate a global variable to 0 (var i = 0) and I light up the first light with:
open(lights[i]);
Since i equals 0, lights[i], so lights[0] is red (In JS, as in most languages, arrays start counting their elements from 0). This way, open(lights[i]) is the same as open(red).
Then I do a setInterval(change, 1000) so every second the function change() is called. And what does this change function do?
Basically:
// Turn off the current light
close(lights[i]);
// Increment i, so that lights[i] points to the next element...
i = (i + 1) % lights.length;
// Turn on this next element
open(lights[i]);
The rarest thing here may be the increment. Why do I do i = (i + 1) % lights.length instead of just i++.
If I do i++ after successive calls to change, i will be: 0, 1, 2, 3, 4, 5, 6... so, when I try to access lights[i] I'll get an error, because there is no element in positions 3, 4, 5... of the lights array.
I need my sequence to be: 0, 1, 2, 0, 1, 2, 0, 1, 2...
How do I get this desired sequence instead of 0, 1, 2, 3, 4, 5, 6... ?
Maybe a more understandable way could be:
i++;
if (i > 2) {
i = 0;
}
But I'm using the Remainder operator (%) to achieve the same effect.
I hope this helps!
And another one with easily configurable duration for every light:
var lights = {
red: {
node: document.getElementById('circleRed'),
duration: 4000,
},
green: {
node: document.getElementById('circleGreens'),
duration: 2000,
},
orange: {
node: document.getElementById('circleOrange'),
duration: 800,
}
};
var order = ['red', 'green', 'orange'];
function open(light) {
light.node.classList.add('opened');
}
function close(light) {
light.node.classList.remove('opened');
}
function change() {
close(lights[order[i]]);
i = (i + 1) % order.length;
open(lights[order[i]]);
setTimeout(change, lights[order[i]].duration);
}
/* Start */
var i = 0;
open(lights[order[i]]);
setTimeout(change, lights[order[i]].duration);
.circle {
width: 50px;
height: 50px;
border-radius: 25px;
margin: 5px;
opacity: 0;
transition: opacity 200ms;
}
.circle.opened {
opacity: 1;
}
#circleRed {
background-color: red;
}
#circleOrange {
background-color: orange;
}
#circleGreens {
background-color: green;
}
.back {
width: 60px;
padding: 5px;
background-color: black;
}
<div class="back">
<div id="circleRed" class="circle"></div>
<div id="circleOrange" class="circle"></div>
<div id="circleGreens" class="circle"></div>
</div>
put all setTimeout( function(){}) in one function, then it will work
Note: to make setInterval work properly, the milliseconds must be at least the total of setTimeout functions.
also you forgot to set the orange to black when the red is appearing.
var red = document.getElementById("circleRed");
var orange = document.getElementById('circleOrange')
var green = document.getElementById('circleGreens');
setInterval(function(){ myTimer() }, 17000);
function myTimer() {
setTimeout( function(){
red.style.backgroundColor = "red";
orange.style.backgroundColor = "black";
}, 2000),
setTimeout(function(){
green.style.backgroundColor = "green";
red.style.backgroundColor = "black";
}, 5000),
setTimeout(function(){
orange.style.backgroundColor = "orange";
green.style.backgroundColor = "black";
}, 10000)
}
myTimer();
#circleRed, #circleGreens, #circleOrange {
width: 50px;
height: 50px;
-webkit-border-radius: 25px;
-moz-border-radius: 25px;
border-radius: 25px;
margin-bottom: 10px;
background-color: "black";
}
.back {
width: 60px;
margin: 10px 0px 10px 20px;
padding-left: 10px;
padding-top: 10px;
padding-bottom: 10px;
background-color: black;
}
body{
margin: 0;
}
<div class="back">
<div id="circleRed">
</div>
<div id="circleOrange">
</div>
<div id="circleGreens">
</div>
</div>
When changing a color of a paragraph element, CSS hover stops working.
I made a demo to explain: https://jsfiddle.net/woan6b64/
After I change <p>'s color, the hover selector stops working.
My question is:
How can I change the hover effect with JavaScript?
How can I get hovering to work after a color change?
JSFiddle code:
var shift = 0;
function change() {
if (shift === 0) {
document.getElementById("box").style.backgroundColor = "black";
document.getElementById("text").style.color = "white";
document.getElementById("text").innerHTML = 'Good! Now click the box again.';
shift = 1;
} else {
document.getElementById("box").style.backgroundColor = "white";
document.getElementById("text").style.color = "black";
document.getElementById("text").innerHTML = 'Hover effect is now broken :(';
}
}
#box {
height: 100px;
width: 200px;
background-color: white;
}
p:hover {
color: green;
}
<div id='box' onclick='change()'>
<p id='text'>
Click me for this box to change color. (Notice how I turn green when hovered)
</p>
</div>
Stop it! Don't use !important if not necessary... your problem is that you set the color to black.
document.getElementById("text").style.color = "";
This will make the color inherit the right style.
How ever, this ain't the right solution either. You should add class to the box and then do:
#box {
height: 100px;
width: 200px;
background-color: white;
}
p:hover {
color: green;
}
#box.altered {
color: white;
background-color: black;
}
.altered p:hover {
color: red;
}
<div id="box" onclick="this.classList.toggle('altered')">
<p id='text'>
Click me for this box to change color. (Notice how I turn green when hovered)
</p>
</div>
Add a new class
// document.getElementById("box").style.backgroundColor = "black";
// document.getElementById("text").style.color = "white";
document.getElementById("text").classList.add("purple");
.purple {
color: purple;
}
If you want to do it with pure JS you need to listen for onmouseover event and onmouseout event, check the code that I made
var textElement = document.getElementById("text");
var defaultColor = textElement.style.color;
textElement.onmouseover = function(event) {
var currentElement = event.target;
currentElement.style.color = "red";
}
textElement.onmouseout = function(event) {
var currentElement = event.target;
currentElement.style.color = defaultColor;
}
<div id="parent">
<p id="text">
I am a text that change its text color :D
</p>
</div>
It's an issue with specificity, so you'll need to use !important on the color property to force it.
fiddle
NB: This isn't best practice. Depending on your intent, adding a class or simply unsetting the color may be the best option.
After setting the color, the hover is overridden. Use !important to force it:
p:hover{
color: green !important;
}
<!DOCTYPE>
<html>
<body>
<img id="traffic" src="assets/red.gif">
<button type="button" onclick="ChangeLights()">Change Lights</button>
<script>
var lights = [
"assets/red.gif",
"assets/yellow.gif",
"assets/green.gif",
"assets/yellow.gif",
];
var index = 0;
function ChangeLights() {
setInterval(function () {ChangeLights();}, 1000);
index = index + 1;
if (index == lights.length) index = 0;
var image = document.getElementById('traffic');
image.src=lights[index];
}
</script>
</body>
</html>
Hi, I am trying to make an animation script using JavaScript so that a traffic light sequence changes from red - yellow - green - yellow on a timer once a button is pressed. I only want the sequence to loop once. However, when I implemented the setInterval function into the function, the lights only change from red - yellow - green - red.
Thank you for any help!
var lights = {
red: "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Traffic_lights_red.svg/200px-Traffic_lights_red.svg.png",
yellow: "https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Traffic_lights_yellow.svg/200px-Traffic_lights_yellow.svg.png",
green: "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Traffic_lights_dark_green.svg/200px-Traffic_lights_dark_green.svg.png"
};
var sequence = ['red', 'yellow', 'green', 'yellow'];
function startChangeLights() {
for (var index = 0; index < sequence.length; index++) {
changeLight(index, sequence[index]);
}
function changeLight(index, color) {
setTimeout(function() {
var image = document.getElementById('traffic');
image.src = lights[color];
}, index * 1000);
}
}
<div>
<img height=100px id="traffic" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Traffic_lights_red.svg/200px-Traffic_lights_red.svg.png">
</div>
<div>
<button type="button" onclick="startChangeLights()">Change Lights</button>
</div>
https://codepen.io/anon/pen/VbKQNj?editors=1011
If you are looking for one time sequence, you have to use "setTimeout" method in javascript and besides, define an inner function like the following:
var lights = [
"assets/red.gif",
"assets/yellow.gif",
"assets/green.gif",
"assets/yellow.gif",
];
var index = 0;
function ChangeLights() {
function innerChangeLight(){
index = index + 1;
if (index == lights.length) index = 0;
var image = document.getElementById('traffic');
image.src=lights[index];
}
innerChangeLight();
setTimeout(function () {
innerChangeLight();
}, 1000);
}
<!DOCTYPE>
<html>
<body>
<img id="traffic" src="assets/red.gif">
<button type="button" onclick="ChangeLights()">Change Lights</button>
</body>
</html>
Try this:
var lights = [
"assets/red.gif",
"assets/yellow.gif",
"assets/green.gif",
"assets/yellow.gif",
];
var index = 0;
function ChangeLights(){
setInterval(function() {
if(index == lights.length) {
return;
}
var image = document.getElementById('traffic');
image.src=lights[index];
index = index + 1;
}, 1000);
}
<img id="traffic" src="assets/red.gif"><br>
<button onclick="ChangeLights()">Change Lights</button>
New instance of 'Traffic Light':
Traffic Lights can't always be the same duration in every light....
So, i started to expand this html code..
The improved code with different seconds in every light:
// Traffic Light
// Improved with different durations in every light!
// But in this html code, i will use input tag instead
var TrafficLights = (function() {
// The image
var imageTag = document.getElementById("lightImg");
// Keep track of whether the sequence is running
var running = false;
// Different stages of the traffic light (Also defines the light)
var stages = [
{
"name": "red",
"path": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Traffic_lights_red.svg/200px-Traffic_lights_red.svg.png",
},
{
"name": "green",
"path": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Traffic_lights_dark_green.svg/200px-Traffic_lights_dark_green.svg.png"
},
{
"name": "yellow",
"path": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Traffic_lights_yellow.svg/200px-Traffic_lights_yellow.svg.png"
}
];
// Different amount of seconds in every light change (Must be an positive integer!)
var seconds_every_step = [
18,
24,
3
];
// Current stage of the traffic light
var stage = 0;
// Current steps of the traffic light
var steps = 0;
// Timer for automatically changing light
var timer = null;
/** * Start the traffic light sequence * */
function start() {
// Mark that the light sequence is running
running = true;
// Tell the light to change
changeLight();
}
/** * Stop the sequence from running * */
function stop() {
// Mark that the sequence is not running
running = false;
// Stop the automatic timer from running
clearInterval(timer);
}
/** * Change the light to the next one in the sequence * */
function changeLight() {
// If the timer is not running, this function does not need to do anything
if (running === false) {
clearInterval(timer);
return;
} else {};
// If the current stage gets higher than the number of stages there are, reset to 0
if (stage >= stages.length) {
stage = 0;
} else {};
// If the current steps gets higher than the number of seconds in a step there are, reset to 0
if (steps >= seconds_every_step.length) {
steps = 0;
} else {};
// Get the image from the list of stages
var image = stages[stage];
var wait_seconds = seconds_every_step[steps];
// Update the image tag and defines the light name
imageTag.src = image.path;
imageTag.alt = String("Traffic light color is " + image.name + ".");
// Increase the current stage by 1
stage++;
// Increase the current steps by 1
steps++;
// Set a timeout to change the light at the next interval
timer = setTimeout(changeLight, wait_seconds * 1000);
}
// These functions will be available on the `TrafficLights` object to allow interaction
return {
start: start,
stop: stop
}
})();
<input type="image" width="20px" id="lightImg" src="" alt="">
<br/>
<p>
<button type="button" onclick="TrafficLights.start()">Start Sequence</button> <button type="button" onclick="TrafficLights.stop()">Stop Sequence</button>
</p>
You may see an error code. Just ignore it...
var red = document.getElementById("red");
var yellow = document.getElementById("yellow");
var green = document.getElementById("green");
var btn = document.createElement("BUTTON");
btn.innerHTML = "CLICK ME";
document.body.appendChild(btn);
red.style.opacity = "1";
yellow.style.opacity = "0.2";
green.style.opacity = "0.2";
btn.onclick = function () {
setTimeout(function(){red.style.opacity = "0.2";yellow.style.opacity = "1"; setTimeout(function(){yellow.style.opacity = "0.2";green.style.opacity = "1"; setTimeout(function(){green.style.opacity = "0.2";red.style.opacity = "1"}, 1000);}, 1000);
}, 1000);
}
html{
background: linear-gradient(#08f, #fff);
padding: 40px;
width: 170px;
height: 100%;
margin: 0 auto;
}
.trafficlight{
background: #222;
background-image: linear-gradient(transparent 2%, #111 2%, transparent 3%, #111 30%);
width: 170px;
height: 400px;
border-radius: 20px;
position: relative;
border: solid 5px #333;
}
#red{
background: red;
background-image: radial-gradient(brown, transparent);
background-size: 5px 5px;
width: 100px;
height: 100px;
border-radius: 50%;
position: absolute;
top: 20px;
left: 35px;
animation: 13s red infinite;
border: dotted 2px red;
box-shadow:
0 0 20px #111 inset,
0 0 10px red;
}
#yellow{
background: yellow;
background-image: radial-gradient(orange, transparent);
background-size: 5px 5px;
width: 100px;
height: 100px;
border-radius: 50%;
border: dotted 2px yellow;
position: absolute;
top: 145px;
left: 35px;
animation: 13s yellow infinite;
box-shadow:
0 0 20px #111 inset,
0 0 10px yellow;
}
#green{
background: green;
background-image: radial-gradient(lime, transparent);
background-size: 5px 5px;
width: 100px;
height: 100px;
border-radius: 50%;
border: dotted 2px lime;
position: absolute;
top: 270px;
left: 35px;
box-shadow:
0 0 20px #111 inset,
0 0 10px lime;
animation: 13s green infinite;
}
<div class="trafficlight">
<div id="red"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
I make a simple HTML and CSS Traffic light from an online example. Then I just create the condition for it to loop red-yellow-green-red.
I'd like to have the css property "color" from div #prueba change each 0.5 seconds between value "blue" and "green" and add this value into the existing div #value but i don't know how to do it, i'd also like it to run in any browser.
body {
text-align: center;
margin: 0;
padding: 0;
}
#prueba {
color: red;
background: grey;
display: inline;
}
<div id="#value"></div>
<div id="prueba">
ABCDE
</div>
setInterval(changeColor, 500)
function changeColor() {
var prueba = document.getElementById('prueba');
if (prueba.style.color === 'blue') {
prueba.style.color = 'green';
} else {
prueba.style.color = 'blue';
}
document.getElementById('value').innerHTML = prueba.style.color;
}
body {
text-align: center;
margin: 0;
padding: 0;
}
#prueba {
color: red;
background: grey;
display: inline;
}
<div id="value"> </div>
<div id="prueba">
ABCDE
</div>
Use the 'setInterval' function
You can use setInterval().
setInterval(function(){
var color = document.getElementById('prueba').style.color; // get current color
var nextcolor = color === "green" ? "blue" : "green"; // decide what color should be next
document.getElementById('prueba').style.color = nextcolor ; // apply to div
document.getElementById('value').innerHTML = nextcolor +'<br />'; // display the color in 'value' div
}, 500); //500 milliseconds == 0.5 seconds
body{text-align:center; margin:0; padding:0;}
#prueba{
color:red;
background:grey;
display:inline;
}
<div id="value">
</div>
<div id="prueba">
ABCDE
</div>