How do I switch lights on a traffic light sequence? - javascript

I'm trying to make a traffic light sequence so that when I press the "change lights" button its supposed to change each time it has been pressed. However, I've the made the code appear with the red light but when I press the "change lights" button it won't change to amber and the other light sequence.
<!DOCTYPE html>
<html>
<body>
<h1>Traffic Light</h1>
<button type="button" onclick="changeLights"()>Change Lights </button>
<script>
var traffic_light = new Array(3)
var traffic_lights = 0
function lights(){
traffic_light = new Image(500,800)
traffic_light.src = "traffic_light_red.jpg";
traffic_light = new Image(500,800)
traffic_light.src = "traffic_light_redAmb.jpg";
traffic_light = new Image(500,800)
traffic_light.src = "traffic_light_green.jpg";
traffic_light = new Image(500,800)
traffic_light.src = "traffic_light_amber.jpg";
}
function changeLights() {
document.traffic_light_images.src = traffic_light[traffic_lights].src
traffic_lights++
if(traffic_lights > 3) {
traffic_lights = 0;
}
}
</script>
<img src = "traffic_light_red.jpg" name "traffic_light_images" height = "500" width = "800">
</body>
</html>

You put the parenthesis outside the quotes onclick="changeLights"()
You don't have an = after the name attribute - do you see it's not the same as the others and not valid html?
You are trying to select a DOM Node with JS that is run before it is inserted in the document (your script tag executes above the image)
You are setting width and height without a unit, and setting width and height like that is not recommended for responsiveness (just advice, not an error). In my example I just let the image naturally fit without specifying.
You are not properly inserting new items into the array, instead you reassigned the array to a new image four times (use push)
var traffic_light = [];
var traffic_lights = 1;
function initLights() {
var image;
image = new Image();
image.src = "http://www.drivingtesttips.biz/images/traffic-light-red.jpg";
traffic_light.push(image);
image = new Image();
image.src = "http://www.drivingtesttips.biz/images/traffic-lights-red-amber.jpg";
traffic_light.push(image);
image = new Image();
image.src = "http://www.drivingtesttips.biz/images/traffic-lights-amber.jpg";
traffic_light.push(image);
image = new Image();
image.src = "http://www.drivingtesttips.biz/images/traffic-lights-green.jpg";
traffic_light.push(image);
}
function changeLights() {
document.traffic_light_images.src = traffic_light[traffic_lights].src;
traffic_lights++;
if (traffic_lights > 3) {
traffic_lights = 0;
}
}
initLights();
<button type="button" onclick="changeLights()">Change Lights </button>
<img src="http://www.drivingtesttips.biz/images/traffic-light-red.jpg" name="traffic_light_images">
However there is no need to create an new image object just to switch the source and your code can be simplified:
const imageBasePath = 'http://www.drivingtesttips.biz/images/';
const traficLights = [
'traffic-light-red.jpg',
'traffic-lights-red-amber.jpg',
'traffic-lights-amber.jpg',
'traffic-lights-green.jpg',
];
const trafficLightImage = document.querySelector('.traffic-light-image');
let trafficLightIndex = 1;
function changeLights() {
trafficLightImage.src = imageBasePath + traficLights[trafficLightIndex];
trafficLightIndex++;
if (trafficLightIndex === traficLights.length) {
trafficLightIndex = 0;
}
}
<button type="button" onclick="changeLights()">Change Lights</button>
<img src="http://www.drivingtesttips.biz/images/traffic-light-red.jpg" class="traffic-light-image" />

Related

Whenever i enter a new url and press click a new image is displaying but the previous image is still there i need to clear the previous image using js

Bhtm
<body>
enter your url<input type="url" id="image">
<button type="button" onclick="display()">click</button>
<script>
function display()
{
var myimage = document.createElement("img");
myimage.src = document.getElementById("image").value + "#" + new Date().getTime();
myimage.style.width = "100px";
myimage.style.height = "120px";
document.body.appendChild(myimage);
}
</script>
</body>
</html>
Seen as the only thing that changes each time is the URL, you could just use a global var to store a reference to the image element, and then just change it's url.
eg.
<script>
var myimage;
function display()
{
//only create image 1 time..
if (!myimage) {
myimage = document.createElement("img");
myimage.style.width = "100px";
myimage.style.height = "120px";
document.body.appendChild(myimage);
}
myimage.src = document.getElementById("image").value + "#" + new Date().getTime();
}
</script>

Only one image appears in an array of 3 images in JavaScript

<img id="opeth"> </img>
<script type="text/javascript">
var gearpics = [];
document.getElementById("opeth").innerHTML = gearpics;
var prs = new Image();
prs.onload = function() {
};
prs.src = src
var prs2 = new Image();
prs2.onload= function() {
};
prs2.src = src
var prs3 = new Image();
prs3.onload= function() {
};
prs3.src = src
function insert() {
gearpics.push(document.getElementById('opeth').src = prs.src);
gearpics.push(document.getElementById('opeth').src = prs2.src);
gearpics.push(document.getElementById('opeth').src = prs3.src);
}
</script>
This is my code. When I run it, and press the "Show pictures" button, only the third picture (id=prs3) appears. I want all of them to show up.
You are using the same ID for your 3 pictures:
gearpics.push(document.getElementById('opeth').src = ...);
ID should be unique in HTML document.

Mouseover Slideshow

So I have a webpage with one image on it (slicedImg_01). I would like to have that static picture animate randomly through a series of 6 pictures on mouseover. So far what I have will randomly generate pictures to the page, however it just creates a new image to the page and doesn't replace the original image. Here is what I have. Also, I am trying to avoid jquery. (slicedImg_02, slicedImg_03, etc.)
HTML:
<body>
<div >
<img onmouseover="imgSwitch()" src="slicedImg_01.gif" height="50" width="50" id = "pic">
</img>
</div>
</body>
JS:
function imgSwitch(){
var img = new Array("slicedImg_01.gif", "slicedImg_02.gif", "slicedImg_03.gif", "slicedImg_04.gif", "slicedImg_05.gif", "slicedImg_06.gif");
var i;
//var pic = ""
for (i = 0; i < 7; i++)
var rand = img[Math.floor(Math.random() * img.length)];
var image = document.getElementById("pic").src
image = new Image();
image.src = rand;
document.body.appendChild(image);
What I don't understand is the line creating a new image image = new Image();. The code below should replace the current image with the randomly selected new image:
function imgSwitch(){
var img = new Array("1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg");
var rand = img[Math.floor(Math.random() * img.length)];
document.getElementById("pic").src = rand;
}
Note the image names need to be replaced with yours.

Want a reverse button for my image Array using JavaScript

Hello I have just created the following JavaScript code for a next button which when clicked will show the next image in my array. However I now want to reverse this by creating a new function for a "Previous" button which goes back down the array rather than forward. This will be much more images than just the 3 example ones you see in this Array:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = "Media//Gallery//img_1.jpg";
imgArray[1] = new Image();
imgArray[1].src = "Media//Gallery//img_2.jpg";
imgArray[2] = new Image();
imgArray[2].src = "Media//Gallery//img_3.jpg";
This is my Next buttons function. I just need to reverse it for the Previous button but not sure how.
function nextImage(event) {
var img = document.getElementById("largeImage");
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src)
{
if(i === imgArray.length){
img.src = imgArray[0].src;
break;
}
img.src = imgArray[i+1].src;
break;
}
}
}
This is the div for the previous button:
<div class="imgNav" onclick="previousImage(this);" style="width:190px">
This is the image which I want to change when you press the button:
<img id="largeImage" src="Media//Gallery//Image_1.jpg" alt="Large Image" />
Thank you so vety much in advance!
This should do it
JavaScript
currentIndex = 0;
function changeImage(direction)
{
var index = currentIndex + direction;
if (index < 0)
{
index = 0; // or use imgArray.length to rotate round
}
if (index > imgArray.length)
{
index = imgArray.length; // or use 0 to rotate round
}
document.getElementById('largeImage').src = imgArray[index].src;
currentIndex = index;
}
Html Code
<div class="imgNav" onclick="changeImage(-1)" style="width:190px">
<div class="OtherimgNav" onclick="changeImage(1)" style="width:190px">

Showing an image from an array of images - Javascript

I have a large image which is shown on my homepage, and when the user clicks the "next_img" button the large image on the homepage should change to the next image in the array.
However, the next arrow when clicked does nothing, and the main image on the homepage does not change.
I need to do this in javascript.
In the HTML:
<!--Main Content of the page -->
<div id="splash">
<img src="images/img/Splash_image1.jpg" alt="" id="mainImg">
</div>
<div id="imglist">
<img src="images/next_img.png" alt="">
And then in the javascript file:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';
imgArray[2] = new Image();
imgArray[2].src = 'images/img/Splash_image3.jpg';
imgArray[3] = new Image();
imgArray[3].src = 'images/img/Splash_image4.jpg';
imgArray[4] = new Image();
imgArray[4].src = 'images/img/Splash_image5.jpg';
imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';
/*------------------------------------*/
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0;i<imgArray.length;i++)
{
if(imgArray[i] == img)
{
if(i == imgArray.length)
{
var j = 0;
document.getElementById(element).src = imgArray[j].src;
break;
}
else
var j = i + 1;
document.getElementById(element).src = imgArray[j].src;
break;
}
}
}
Any help would be appreciated. Thanks.
Just as Diodeus said, you're comparing an Image to a HTMLDomObject. Instead compare their .src attribute:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';
/* ... more images ... */
imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';
/*------------------------------------*/
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src) // << check this
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
Here's a somewhat cleaner way of implementing this. This makes the following changes:
The code is DRYed up a bit to remove redundant and repeated code and strings.
The code is made more generic/reusable.
We make the cache into an object so it has a self-contained interface and there are fewer globals.
We compare .src attributes instead of DOM elements to make it work properly.
Code:
function imageCache(base, firstNum, lastNum) {
this.cache = [];
var img;
for (var i = firstNum; i <= lastnum; i++) {
img = new Image();
img.src = base + i + ".jpg";
this.cache.push(img);
}
}
imageCache.prototype.nextImage(id) {
var element = document.getElementById(id);
var targetSrc = element.src;
var cache = this.cache;
for (var i = 0; i < cache.length; i++) {
if (cache[i].src) === targetSrc) {
i++;
if (i >= cache.length) {
i = 0;
}
element.src = cache[i].src;
return;
}
}
}
// sample usage
var myCache = new imageCache('images/img/Splash_image', 1, 6);
myCache.nextImage("foo");
Some advantages of this more object oriented and DRYed approach:
You can add more images by just creating the images in the numeric sequences and changing one numeric value in the constructor rather than copying lots more lines of array declarations.
You can use this more than one place in your app by just creating more than one imageCache object.
You can change the base URL by changing one string rather than N strings.
The code size is smaller (because of the removal of repeated code).
The cache object could easily be extended to offer more capabilities such as first, last, skip, etc...
You could add centralize error handling in one place so if one image doesn't exist and doesn't load successfully, it's automatically removed from the cache.
You can reuse this in other web pages you develop by only change the arguments to the constructor and not actually changing the implementation code.
P.S. If you don't know what DRY stands for, it's "Don't Repeat Yourself" and basically means that you should never have many copies of similar looking code. Anytime you have that, it should be reduced somehow to a loop or function or something that removes the need for lots of similarly looking copies of code. The end result will be smaller, usually easier to maintain and often more reusable.
Also, when checking for the last image, you must compare with imgArray.length-1 because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:
if(i == imgArray.length-1)
This is a simple example and try to combine it with yours using some modifications. I prefer you set all the images in one array in order to make your code easier to read and shorter:
var myImage = document.getElementById("mainImage");
var imageArray = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg",
"_images/image4.jpg","_images/image5.jpg","_images/image6.jpg"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex = (imageIndex + 1) % imageArray.length;
}
setInterval(changeImage, 5000);
Here's your problem:
if(imgArray[i] == img)
You're comparing an array element to a DOM object.
<script type="text/javascript">
function bike()
{
var data=
["b1.jpg", "b2.jpg", "b3.jpg", "b4.jpg", "b5.jpg", "b6.jpg", "b7.jpg", "b8.jpg"];
var a;
for(a=0; a<data.length; a++)
{
document.write("<center><fieldset style='height:200px; float:left; border-radius:15px; border-width:6px;")<img src='"+data[a]+"' height='200px' width='300px'/></fieldset></center>
}
}

Categories

Resources