Different intervals between images - javascript

I am studying for GCSE computing and need to be able to change the interval between different images. My code at the moment looks something like this...
<!DOCTYPE html>
<html>
<body>
<h1> Traffic lights can change on their own </h1>
<img src="RED.jpg" id= "traffic" width="155" height="198">
<script>
var myImage = document.getElementById("traffic");
var imageArray = ["RED.jpg", "RED-ORANGE.jpg", "GREEN.jpg", "ORANGE.jpg"];
var imageIndex = 0;
function changeImage()
{
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage,1000);
</script>
</body>
</html>+
If you could include some of this code whilst changing the intervals that would be ideal.

Supposing you want to solve this using Javascript only:
Source documentation
// Save the var timeoutID = window.setTimeout(code, [delay]);
var imageTimers = [500, 1000, 2000, 4000];
var timeTochange = Math.random() * 3000; // or whatever you want to use...
var aTimer = setTimeout(changeImage, timeTochange);
// On the changeImage, alter the timeTochange var.
function changeImage() {
// ...stuffs...
clearTimeout(aTimer);
timeTochange = imageTimers[imageIndex];
aTimer = setTimeout(changeImage, timeTochange);
}

Related

How to make images appear randomly in Javascript?

I need to create a web page with a button that says "start game". When this button is clicked, 5 images I have downloaded (img1.png...img5.png) must appear randomly, one at a time, every half a second. Here is my code so far, any help would be greatly appreciated!
<html>
<head>
<script>
var rollImagesSchedule;
var rollImagesCounter;
function rollImagesAnimation(){
rollImagesCounter = 0;
rollImagesSchedule = setInterval(500);
}
function rollImages(){
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
rollImagesCounter = rollImagesCounter + 1;
if (rollImagesCounter == 10){
clearInterval(rollImagesSchedule);
}
}
</script>
</head>
<body>
<h1>Game</h1>
<button onClick="rollImagesAnimation()">Start frog game</button>
<br /><br />
<img id="display" style='width:200px; height:200px;'>
</body>
</html>
I think you're getting stuck with the way to use setInterval.
You can try to create a counter outside setInterval function, and nest all of your works inside of it. And the counter should be checked at the top.
function rollImages(){
var counter = 0;
var interval = setInterval(function () {
if (counter === 10) {
clearInterval(interval);
return;
}
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
counter++;
}, 500);
}
Then, you can edit the way to catch event rollImages:
<button onClick="rollImages()">Start frog game</button>
My English is not very good, so I might misunderstand your question. Let me answer it according to what I understand.
Your requirement is to randomly display one of the five pictures every 500 milliseconds, right? If so, you can try this idea:
Put the src of 5 pictures into an array
var imageSrcs = ["image1","image2","image3","image4","image5"];
Every 500 milliseconds, execute the following function:
function rollImages(){
// Randomly generate a random number between 0-4
int index = Math.floor(Math.random() * 5) + 1;
var theImage = document.getElementById("display");
// Use random numbers as subscripts and take values from the array
theImage.src = imageSrcs[index];
}
You can store the images name files into an array and then setInterval a random number and assign the source of an img html element:
var list = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
];
var i = 0;
function changeImgs() {
var imageValue = Math.floor(Math.random() * list.length - 1) + 1;
image.src = list[imageValue];
}
setInterval(function() {
changeImgs()
}, 2000);
window.onload = changeImgs;
<img id="image" class="size">

error on trying to change image in sequence from list JavaScript

I have a list:
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
I made a code which attempts at displaying image1 when the page loads but for ever 3 seconds the image changes to the next image in the list. However when the code was ran it was stuck on image1 and did not change in the next 3 seconds.
This is my JavaScript code so far:
<html>
<body>
<body onload = "myFunction()">
<img src ="image1.png" id = "target" >
<script language="javascript">
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 4) {
counter = 0
}
target = document.getElementById ("target").src = images[counter];
setTimeout("myFunction", 3000)
}
window.onLoad = function(){
myFunction();
}
</script>
</body>
</html>
I have seen similar codes but the answers answered did not meet my specification.
You can use setInterval (passing a function rather than a string) instead of recursively calling setTimeout. Also note that your counter logic can be greatly simplified with the use of the modulo (%) operator:
<html>
<body>
<img src="image1.png" alt="image1.png" id="target">
<script language="javascript">
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
var target = document.getElementById("target")
setInterval(function myFunction() {
counter = (counter + 1) % images.length
target.src = target.alt = images[counter]
}, 3000)
</script>
</body>
</html>
In setInterval, you need to pass the function myFunction as parameter, not the function name "myFunction":
Change it to this:
setTimeout(myFunction, 3000);
setTimeout - will work only one time
setInterval - will continue always
<html>
<body>
<img src ="logo.png" id = "target" >
<script language="javascript">
var counter = 0;
var images = ["logo.png", "222.jpg"];
function myFunction() {
counter++;
if (counter > 1) {
counter = 0
}
target = document.getElementById("target").src = images[counter];
}
function my2(){
setInterval("myFunction()", 1000);
}
window.onload = function(){
my2();
}
</script>
</body>
</html>
Expanding on what others have mentioned already.
It's window.onload - not window.onLoad - Casing is important
Update to
setTimeout(myFunction, 3000);
Place that in your window.onload
JS:
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 4) {
counter = 0
}
target = document.getElementById ("target").src = images[counter];
}
window.onload = function(){
setTimeout(myFunction, 3000)
}
You can use setInterval instead of setTimeout
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 3) {
counter = 0
}
target = document.getElementById("target").src = images[counter];
}
setInterval(myFunction, 3000);
JSFiddle

Changing picture frame with toggle button

Ok so we have a simple user info editing page.I want to create a toggle button which swaps profile picture border-radius from 0 to 25 and backwards.But the 2nd part doesnt work.I created if to check if the boarder radius is 25 already so it will make it 0, but it does not work.Here is my code
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="buildImage();">
<div class="contents" id="content"></div>
<button onclick="changeImage()">NextImage</button>
<button onclick="changeShape()">ChangeShape</button>
<button onclick="uploadImage()">Upload Image</button>
</body>
<script>
var images = [ 'profile1.png', 'profile2.png','profile3.png'];
var index = 0;
var array_length = 3;
function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
function changeImage(){
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % array_length;
img.src = images[index];
}
function changeShape(){
var shape = document.getElementById('content').getElementsByTagName('img')[0].style.borderRadius = "25px";
if(shape.style.borderRadius == 25){
var shape2 = document.getElementById('content').getElementsByTagName('img')[0].style.borderRadius = "0px";
}
}
function uploadImage() {
images.push("profile4.png");
array_length++;
}
</script>
</html>
Any ideas why it doesnt work?
You are uselessly assigning variables in your function by the looks of it.
There is no need to declare shape2. Just declare shape once and then use that to check. Also make sure to check shape.style.borderRadius against a string like "25px" as that will be returned.
Try something like this:
function changeShape(){
var shape = document.getElementById('content').getElementsByTagName('img')[0];
if(shape.style.borderRadius == "25px"){
shape.style.borderRadius = "0px";
}else{
shape.style.borderRadius = "25px";
}
}

How to choose random image from image set in javascript

I have been using the following code to generate random images, but none of the pictures are showing up.
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
var theImages = new Array()
theImages[0] = '<img class="atvi-image-image" alt=""src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png" title="" height="467" width="675">'
theImages[1] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png" title="" height="732" width="1084">'
theImages[2] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-extra-slots.png" title="" height="480" width="752">'
theImages[3] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-2025.png" title="" height="412" width="683">'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write(theImages[whichImage]);
}
</script>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
</body>
</html>
Thank you in advance for your help!
You already have the full <img> tag in the array. So just use:
document.write(theImages[whichImage]);
Although I would advise against using document.write. Of course, in your situation, where it's being executed in the middle of HTML, I don't see much of a problem. It would be bad if document.write were executed after the page was rendered. Normally, the preferred method is something like the appendChild method or even setting innerHTML, although it would take some refactoring to get your code to use them.
Here's an example of how I'd set it up:
(function () {
var theImages = [{
src: "http://www.techinasia.com/techinasia/wp-content/uploads/2009/12/smile.png",
width: "675",
height: "467"
}, {
src: "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQdcHlJqgIKNOS0DaEjO31xK1zYtmJlza8z70ljiKFbo2ZgLdh9eA",
width: "1084",
height: "732"
}, {
src: "http://cdn2-b.examiner.com/sites/default/files/styles/large_lightbox/hash/68/d1/68d11ab242d40c8d5abbe8edb58fd4ed_0.jpg?itok=M3qtK47_",
width: "200",
height: "200"
}];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
preBuffer[i].width = theImages[i].width;
preBuffer[i].height = theImages[i].height;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.getRandomImage = function () {
var whichImage = getRandomInt(0, preBuffer.length - 1);
return preBuffer[whichImage];
}
})();
window.onload = function () {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
DEMO: http://jsfiddle.net/wFjGv/
This code uses a new object to hold the details for each image. That way, you can easily set and get each image's properties that you need without hardcoding HTML.
It preloads the images in the preBuffer array, and when needed, an image is retrieved from the array, and put into the <body>. You can change its target in the onload event. The getRandomImage function returns a random image from that array. I updated the method of getting a random integer as well.
You are setting an <img src= something that is not what you want. Your array (theImages) is storing full <img> tags, not just the link to that image.
Either change you theImages array to store values like so:
theImages[0] = "/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png"
OR use the current setup as the image tag.
document.write(theImages[whichImage]);
Also:
With random numbers, you should probably stick to Math.floor() lest
you round over your max length.
var j = 0 is missing a ;
theImages img tags are not closed (<img ... />
Try this-
var srcs = [
"/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png",
"/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png",
"foo/bar.jpg"
], imgs = [];
function init() {
"use strict";
var i, x, div;
div = document.createElement('div');
div.id = 'imageContainer';
document.querySelector('body').appendChild(div);
for (i = 0; i < srcs.length; i += 1) {
x = new Image();
x.src = srcs[i];
imgs.push(x);
}
}
function showRandom() {
"use strict";
document.querySelector('#imageContainer').innerHTML = imgs[Math.random * imgs.length];
}
init();
To add a random image-
showRandom();
PS - You shouldn't use document.write, but if you do, you should close the stream by document.close, to tell the browser to finish loading the page. Read more - MDN JS Docs

loop a series of image in javascript

i want to loop a series of images in javascript. below is the code i have so far
<html>
<head>
</head>
<body>
<img src="images/image1.jpg" alt="rotating image" width="600" height="500" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator'); // change to match image ID
//var imageDir = 'images/'; // change to match images folder
var delayInSeconds = 1; // set number of seconds delay
// list image names
var images = ['1.jpg','2.jpg', '3.jpg', '4.jpg'];
// don't change below this line
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 50);
})();
</script>
</body>
</html>
It can only display the image i have declared in the "var image". if i have 10000 image , how to do that . I have tried using a 'for' loop but it failed .. any suggestions ?? thanks in advance
==============================================================
update version that Joseph recommend :
<html>
<head>
</head>
<body>
<img src="images/1.jpg" alt="rotating image" width="600" height="500" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator'), //get the element
var delayInSeconds = 1, //delay in seconds
var num = 0, //start number
var len = 9999; //limit
setInterval(function(){ //interval changer
num = (num === len) ? 0 : num; //reset if limit reached
rotator.src = num + '.jpg'; //change picture
num++; //increment counter
}, delayInSeconds * 1000);
}());
</script>
</body>
</html>
Assuming that images have the same sequential filenames, this would be best when looping through a lot of them:
(function() {
var rotator = document.getElementById('rotator'), //get the element
dir = 'images/', //images folder
delayInSeconds = 1, //delay in seconds
num = 0, //start number
len = N; //limit
setInterval(function(){ //interval changer
rotator.src = dir + num+'.jpg'; //change picture
num = (num === len) ? 0 : ++num; //reset if last image reached
}, delayInSeconds * 50);
}());
AFAIK, you can use the same logic to display the images in small chunk as your browser will crash if you try to display all 10000 images at the same time.So display 5-10 images on the page with your current logic and ask the user to retrieve next set.You can see this kind of implementation in many image sharing applications.Hope this will help you
(function () {
var rotator = document.getElementById('rotator'); // change to match image ID
var imgDir = 'images/'; // change to match images folder
var delayInSeconds = 1; // set number of seconds delay
// Yes I made changes below this line
var num = 0;
var changeImage = function () {
rotator.src = imgDir + num++ + ".jpg";
//var len = rotator.src.length;
if (num == 5) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();

Categories