How can I change an image with onclick() & if statement repeatedly? - javascript

I am new to javascript and need some help with an issue.
I have 3 traffic light images that I want to change with each click. Go from green to amber with one click, then amber to red with another click, then from red to green, etc.
I have some code below, but it seems to go from green to red with the first click.
Any help is appreciated.
Thanks.
<!DOCTYPE html>
<html>
<body>
<button onclick="nextLight()">Click here</button>
<img id="demo" src="green.png">
<script>
function nextLight() {
var lights = ["blank.png", "green.png", "amber.png", "red.png"]
if (document.getElementById("demo").src == lights[1]) {
document.getElementById("demo").src = lights[2];
} else if (document.getElementById("demo").src == lights[2]) {
document.getElementById("demo").src = lights[3];
}
}
</script>
</body>
</html>

You have the lights array as the possible states. All you need is to iterate between them.
There is a problem with the time it takes to load the amber and red images for the 1st time, as they are loaded only when the state changes. I've added a little preloader to solve that problem.
fiddle demo - note that I use other images in the demo
var demo = document.getElementById("demo"); // get the demo element and cache it
var lights = ["green.png", "amber.png", "red.png"]; // array of lights srcs
var currentLight = 0; // current light index holder
lights.forEach(function(src) { // image preloader
new Image().src = src;
});
function nextLight() {
currentLight++; // add one to currentLight index
currentLight > 2 && (currentLight = 0); // if it's above 2 change it back to 0
demo.src = lights[currentLight]; // assign the url to the src
}

To do this, i think this way is much easier :
var lights = ['', '', '', ''];
var currentLight = 0;
// This version will loop (Go from red to blank at the end)
function nextLight() {
currentLight = (currentLight + 1) % lights.length;
document.getElementById("demo").src = lights[currentLight];
}
// This version do what you want (no loop, just display each image and then do nothing)
function nextLight() {
// Test if the next is not out of range
if(currentLight + 1 < lights.length - 1) {
document.getElementById("demo").src = lights[++currentLight];
}
}

I would suggest using a switch statement:
function nextLight() {
var demo = document.getElementById("demo");
var lights = [
"", // blank
"http://i.imgur.com/oisXdU3.png", // green light
"http://i.imgur.com/qmwYgq7.png", // orange light
"http://i.imgur.com/fs6Rl1W.png" // red light
];
switch(demo.src){
case lights[1] : demo.src = lights[2]; break;
case lights[2] : demo.src = lights[3]; break;
case lights[3] : demo.src = lights[1]; break;
}
}
<button onclick="nextLight()">Click here</button>
<img id="demo" src="http://i.imgur.com/oisXdU3.png" height="100">

Related

how to change an image based on an if statements requirements

var mpegArray = ["1.m4a", "2.m4a", "3.m4a", "4.m4a", "5.m4a", "6.m4a", "7.m4a", "8.m4a", "9.m4a", "10.m4a"];
var choice = Math.floor(Math.random() * mpegArray.length);
function btnPlay_onClick() {
var player = document.getElementById('sound');
player.src = mpegArray[choice];
player.play();
player.addEventListener('ended', function () {
if (player.ended) {
mpeg();
}
}, true);
}
function btnN1_onClick() {
var Audio1 = document.getElementById("audio1");
Audio1.play();
if (choice == 0) {
document.getElementById("btnN1").src = "1GR.gif";
ans.innerText = CORRECT;
}
else
document.getElementById("btnN1").src = "1RD.gif";
ans.innerText = INCORRECT;
}
hiya the code here is meant to get number tiles to change colour based on if the requirements of the if statements are met. here the if statement is asking if button 1 is pressed after the audio file 1.m4a is played change the colour of he tile to green if not change it to red
You might be better served changing the css with a background colour/image instead of the src attribute.
document.getElementById("btnN1").style.backgroundColor = "green";
or
document.getElementById("btnN1").style.backgroundImage = "url('1GR.gif')";
EDIT: GiaFil7 is right. You're missing a closing } after the second if statement which might be causing your issue.

I'm Trying to Change My Background, But it Doesn't Work. What's Wrong?

I'm trying to create some javascript that will change the body's background-color every second. I researched it and came up with this code, but it didn't work.
var x;
function changecolors() {
x = 1;
setTimeout(change, 1000);
}
function change() {
if (x === 1) {
color = "blue";
x = 2;
}
if (x === 2) {
color = "green";
x = 3;
}
if (x === 3) {
color = "red";
x = 1;
}
document.body.style.background = color;
}
Is there anything wrong with this code?
setTimeout() : To execute a function only once, after a specified number of milliseconds.
setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
Resource : https://www.w3schools.com/jsref/met_win_setinterval.asp
Note : You Change x to 1 , 2 and 3 , I think you want change background color blue,green,red after 1000ms :
So Use setInterval instead of setTimeout :
Full Code:
var x=1;
setInterval (change,1000);
function change() {
if (x === 1) {
color = "blue";
x = 2;
}
else if (x === 2) {
color = "green";
x = 3;
}
else if (x === 3) {
color = "red";
x = 1;
}
document.body.style.background = color;
}
here what I can see is you have decleared the function but have you called the function changecolors(); ?
In your original code, your 2nd and 3rd ifs should be made into else ifs; otherwise, you'll always get red. This is because you hit the 1st if since x === 1, then immediately hit the 2nd if (since now x === 2) and finally, hit the last if (since now x === 3) and by the end of every function call, you will have color === 'red' and x === 1.
Beside that, if you want it to cycle every second, you either have to re-call setTimeout(change, 1000); at the end of your function because setTimeout only fires once per call; Or, you can use setInterval(change, 1000); instead, which will run every second on its own.
Consider something like this instead, which will cycle through an array of colors, by incrementing (and then resetting back to 0, using the % operator) your variable and accessing an array, rather than using ifs.
var x;
var colors = ['blue', 'green', 'red'];
function changecolors() {
x = 0;
setInterval(change, 1000);
}
function change() {
document.body.style.background = colors[(x++) % colors.length];
}
changecolors();
Please have a look at my commented solution:
var lightnumber = 0; // this variable saves the current state of the background lights
var lights = [
"#ff0000", "#ffff00", "#00ff00"
]; // this variable saves all possible lights. You can also use "red", "green", "yellow" or whatever is acceptable for CSS.
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.body.style.background = lights[lightnumber];
// and lastly, call the function again after a second
setTimeout(setBgColour, 1000);
}
<h1>Traffic Light</h1>
</br>
<button id="next" onClick="setBgColour()" type="button">Next</button>
</div>
You've errors in your code. Check that example from W3CSchools
<!DOCTYPE html>
<html>
<body>
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
setTimeout(function(){ alert("Hello"); }, 3000);
}
</script>
</body>
</html>
As you can see – set Timeout is NOT like delay(3000) (from other language) or something like that. You can learn a bit trying (it wouldn't work) to make it pausing, not deploying with delay. You will see then it's not pausing whole script, but only running that what's inside with delay. Check it:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
setTimeout(function(){ alert("It will be first? Not!"); }, 6000);
setTimeout(function(){ alert("It will be second? Not!"); }, 2000);
}
</script>
</body>
</html>
And now solution.
var timeout = 1000; //time of delay (in ms)
var backgroundColors = ["blue", "green", "red"]; //table with colors for background
var fingerOnColorsArr = 0; //var that'll store actual position, just like your's x var
var action = function() //definition of function that'll change background color
{
document.body.style.background = backgroundColors[fingerOnColorsArr];
fingerOnColorsArr++; //just go forward
//if we're out of array's reach – go back to begin
if (fingerOnColorsArr == backgroundColors.length)
{
fingerOnColorsArr = 0;
}
};
//execute function `action` in infinite loop with interval `timeout`:
setInterval(action, timeout);
You can modify first two lines and simply change interval or colors pattern. By the way – it's possible to make it shorter, but as I can see – you're newbie, so more important is understanding everything what's code doing.

Automatic slideshow with PHP and JavaScript

So basically i have made a PHP program that takes pictures from a folder and puts it into the "slideshow" in Gallery. The PHP code gives the images id's starting from "1" and so on.
Now with JavaScript i want it to automatically switch picture every 2,5 second. It actually runs as i want it to in my Firebug Script, but nothing happens in the browser. I already posted my JavaScript link in the bottom of the HTML body, and it doesn't help.
Any help would be appreciated.
<div id="gallery" class="grey">
<h3>Gallery</h3>
<div id="slideshow">
<?php
$path = "./img/gallery";
$all_files = scandir($path);
$how_many = count($all_files);
for ($i=2; $i<$how_many;$i++) {
$kubi=$i - 1;
echo "<img src=\"./img/gallery/$all_files[$i]\" id= \"$kubi\"/>";
}
?>
</div>
</div>
JavaScript code:
var picture = document.getElementById("1");
var i = 0;
function rotateImages() {
while (i < document.getElementById("slideshow").childNodes.length) {
picture.style.display = "none";
picture = picture.nextSibling;
picture.style.display = "inline";
i++;
};
};
window.onload = function(){
document.getElementById("1").style.display = "inline";
setInterval(rotateImages(), 2500);
};
What happens is that always uses the same first element picture, hides it and then shows the second image, it does not actually iterate through all the pictures.
In your code, picture always is the first element, next is always the second.
Also, it should not be a while loop since the callback is called once to change a picture, so change it to if, and reset to the first picture when it passes number of total elements.
It should be: (Javascript)
var firstPicture = document.getElementById("1");
var picture = firstPicture ;
var i = 0;
function rotateImages() {
// hide current element
picture.style.display = "none";
// choose who is the next element
if (i >= document.getElementById("slideshow").childNodes.length) {
i = 0;
picture = firstPicture;
} else {
picture = picture.nextSibling;
}
// show the next element
picture.style.display = "inline";
i++;
};
window.onload = function(){
var curImg = document.getElementById("1").style.display = "inline";
setInterval(rotateImages, 2500);
};

adding a click event to confirm image color javascript

I was writing a javascript game so that everytime 4 different random colors are placed on the screen as images and the player is asked to click on the green color, however I cant find what to write on the click function even after searching so much, also how to I make the images keep changing automatically every few say for example 2 seconds
heres how the game works :
when the page loads, 4 blank white images are shown
after clicking on the start button 4 different colors take place of the blank image
after clicking on the green image the game should say alert something
I used 0-5 code for colors on the script for img src 0.jpg being for white , 1-4 green red blue brown respectively
any help would be appreciated
the code : http://jsfiddle.net/gf2un/1/
JS
var counter = 0;
var greenNumber;
function start() {
var button = document.getElementById("startButton");
button.addEventListener("click", generateColor, false);
}
function generateColor() {
var color;
var imgCheck = [];
for (var i = 1; i <= 4; ++i) {
do
color = Math.ceil(Math.random() * 4);
while (imgCheck.indexOf(color) !== -1)
if (color == 1) greenNumber = i;
imgCheck[i] = color;
setImage(i, color);
}
}
function setImage(rdmNumber, color) {
var rdmImg = document.getElementById("color" + rdmNumber);
rdmImg.setAttribute("src", "images//" + color + ".jpg");
rdmImg.setAttribute("width", "90px");
}
function Click( clickedImage )
{
var theSrc = clickedImage.src;
if (theSrc = "image/1.jpg")
++counter;
document.getElementById('score').innerHTML = "Score : " + counter;
}
window.addEventListener("load", start, false);
HTML
<center>
<p>CLICK ON THE GREEN SQUARE</p>
<p>
<img id = "color4" src = "images/0.jpg" alt = "box 1 image" width = "90px" onClick = "Click(this)">
<img id = "color1" src = "images/0.jpg" alt = "box 2 image" width = "90px" onClick = "Click(this)">
</p>
<p>
<img id = "color2" src = "images/0.jpg" alt = "box 3 image" width = "90px" onClick = "Click(this)">
<img id = "color3" src = "images/0.jpg" alt = "box 4 image" width = "90px" onClick = "Click(this)">
</p>
<form action = "#">
<input id = "startButton" type = "button" value = "Start">
</form>
</center>
</body>
You are doing it too complex; you don't need to create REAL images. Instead, play with the css a little. It makes the code look more neat, and the player doesn't require to download the images.
Shuffling is easy, when you are using a container.
Add click functions with method addEventListener(). This adds an event to the HTML object, so you can add more than one function to it.
Here's my working version of your game: http://jsfiddle.net/kychan/k3J9b/1/ Try it! No seriously, i made this game for you! Inspect it, copy it or use it fully, it's all yours! I also added lots of comments for you.
Shuffle example:
// changes the color and shuffles the deck.
function newColor() {
// we change the color we want the user to press.
var rand_color = randomValue(colors);
curColor.innerHTML = rand_color;
// we also change the color of the span, so it changes the text color.
curColor.style.color = rand_color;
// we shuffle constant SHUFFLE_MAX times and re-add it to the container.
for (var i=0; i<SHUFFLE_MAX; i++) {
container.appendChild( randomValue(boxes) );
}
}
returns a random value in the array:
function randomValue(array) {
return array[(Math.floor(Math.random()*array.length))];
}

Simple JavaScript image rotator

I have a simple image rotator on a website consisting of 4 images that have to appear for a few seconds before showing the next one. It seems to work on its first cycle but then when it gets back to the first image it doesn't show that one but works again from the second image and so on always missing that image on every cycle.
The function is called using onLoad EH in the body. In the body there is an img with my first image inside it. I'm a noob so please be gentle if I've missed anything out.
Here's what I have...
<body onLoad="sunSlideShow()">
<img src="IMAGES/slider1.gif" alt="slide-show" id="mySlider" width="900">
<body>
var quotes = new Array ("slider2.gif", "slider3.gif" ,"slider4.gif", "slider1.gif");
var i = 0
function sunSlideShow()
{
document.getElementById("mySlider").src = ( "IMAGES/" + quotes[i] );
if (i<4)
{
i++;
}
else
i = 1;
setTimeout("sunSlideShow()", 3000);
}
sunSlideShow()
Change it to this:
else
i = 0;
setTimeout("sunSlideShow()", 3000);
Further to my other answer (which was wrong!)... Try this:
http://jsfiddle.net/pq6Gm/13/
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(sunSlideShow,3000);
});
var quotes = [
"http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2007/07/11/sun128.jpg",
"http://icons.iconarchive.com/icons/robinweatherall/seasonal/128/sun-icon.png",
"http://www.astronomytoday.com/images/sun3.gif",
"http://mariusbancila.ro/blog/wp-content/uploads/2011/08/sun.png"
];
var i = 0;
function sunSlideShow() {
document.getElementById("mySlider").src = quotes[i];
if (i < (quotes.length-1))
{
i++;
}
else
{
i = 0;
}
}
</script>
<body>
<img src="http://mariusbancila.ro/blog/wp-content/uploads/2011/08/sun.png" id="mySlider"/>
</body>
==================================================================
EDIT: This is wrong... please find my other answer on this page.
==================================================================
To start with, I wouldn't use ... you're better off starting the script with jquery once the page is loaded.
Add this to your head section:
<script type="text/javascript">
$(function () {
sunSlideShow();
}
</script>
That will fire the sunSlideShow function once the page is loaded.
Then, you're starting your slideshow with var i = 0... but when you've got to the fourth image, you're setting it to 1?
I would be tempted to use a while loop to achieve what you want.
Something like this:
<script type="text/javascript">
$(function () {
sunSlideShow();
}
var quotes = new Array ("slider2.gif", "slider3.gif" ,"slider4.gif", "slider1.gif");
var i = 0;
function sunSlideShow(){
while (i<4)
{
document.getElementById("mySlider").src = ( "IMAGES/" + quotes[i] );
if (i<4)
{
i++;
}
else
{
i = 0;
}
sleep(3000);
}
}
function sleep(miliseconds){
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()){}
}
</script>
This script hasn't been tested... but it should start the sunSlideShow function once the page has loaded and then change the image every 3 seconds.
I too searched the web trying to find a general solution to the problem of rotating an image about its center. I came up with my own solution which works perfectly. The basic concept is simple: rotate the entire context by the desired angle (here called 'tilt'); calculate the image's coordinates in the NEW coordinate system; draw the image; lastly, rotate the context back to its original position. Here's the code:
var xp = rocketX * Math.cos(tilt) - rocketY * Math.sin(tilt);
var yp = rocketX * Math.sin(tilt) + rocketY * Math.cos(tilt);
var a = rocketX - xp;
var c = Math.sqrt(a*a + (rocketY-yp)*(rocketY-yp));
var beta = Math.acos(a/c);
var ap = c * Math.cos(tilt + beta);
var bp = c * Math.sin(tilt + beta);
var newX = rocketX + ap;
var newY = rocketY - bp;
context.rotate(tilt);
context.drawImage(littleRocketImage, newX-9, newY-40);
context.rotate(-tilt);
In the penultimate line, the constants '9' and '40' are half the size of the image; this insures that the rotated image is placed such that its center coincides with the center of the original image.
One warning: I use this only for first quadrant rotations; you'll have to put in the standard tests for the other quadrants that change the signs of the components.
Update: 2021
You can use the light-weight library Ad-rotator.js to setup simple Ad-rotation like this -
<script src="https://cdn.jsdelivr.net/npm/ad-rotator"></script>
<script>
const instance = rotator(
document.getElementById('myelement'), // a DOM element
[ // array of ads
{ url: 'https://site1.com', img: 'https://example/picture1.jpg' },
{ url: 'https://site2.com', img: 'https://example/picture1/picture2.jpg'},
// ...
]
);
</script>
<body onLoad="instance.start()">
<div id="myelement"></div>
<body>
Reference Tutorial

Categories