How to make images appear randomly in Javascript? - 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">

Related

how to change the picture on a page without a button or without hovering over it

I have to make a program which is able to present an animation once opened.
Here the code that I have so far, but I am not sure how to fix it to automatically show the pictures and I am not allowed to use a button or hover over the image to change it , and I'm not allowed to use a premade gif or a gif at all
var index = 0;
var ImageList = ["http://www.iconsplace.com/icons/preview/orange/happy-256.png", "http://www.iconsplace.com/icons/preview/orange/sad-256.png"];
var image1 = document.getElementById("myImage");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if (timerValue >= 30) {
img.src("http://www.iconsplace.com/icons/preview/orange/happy-256.png");
} else if (timer <= 60) {
img.src("http://www.iconsplace.com/icons/preview/orange/sad-256.png");
} else {
img.src("http://www.iconsplace.com/icons/preview/orange/happy-256.png");
}
}
<img id="myImage" src="http://www.iconsplace.com/icons/preview/orange/happy-256.png" style="width:200px">
You can use an interval:
window.onload = function(){
var index = 0;
var ImageList = ["Images/happy.png", "Images/sad.png"];
var image1 = document.getElementById("myImage");
var a = 0;
setInterval(function(){
a++;
image1.src = ImageList[a % ImageList.length];
}, 30000);
}
It changes the image per 30 seconds.
You have the two images in an array. USE it!
var index = 0;
var ImageList = ["http://www.iconsplace.com/icons/preview/orange/happy-256.png", "http://www.iconsplace.com/icons/preview/orange/sad-256.png"];
window.onload=function() { // page has finished loading, image is available
var image1 = document.getElementById("myImage");
var tId=setInterval(function() {
index=index==0?1:0; // if 0 then 1 else 0
// for more images instead use:
// index++; if (index>=ImageList.length)index=0;
image1.src=ImageList[index]; // how to set the image src
},5000); // every 5 seconds
}
<img id="myImage" src="http://www.iconsplace.com/icons/preview/orange/happy-256.png" style="width:200px">

Do/while loop not counting number of rolls or lining up with dice

I'm just learning javascript and my project is to create a web page with the following elements: An h2 header, two img elements, an input box, and a button element. When the page loads, Dice.getURL is called twice to get the URL for the 1-dot die, and the jQuery.attr() function is used to display the images when the page loads: When the user enters a target number and clicks Roll 'em!, the images are updated die-namically and the results displayed in a div on the page.
I've got the basics down but I have no idea how to do the rest of this stuff. I've been looking online but haven't found what I needed. I hope you guys can be what I need:
The main issue that I have is that the numRolls variable is not keep track of how many times the do/while loop runs through. I am also confused on how to keep track of the dice rolls via images so it displays the correct output when the "solution is found"
Here is a link to my jsfiddle: https://jsfiddle.net/0088v6nt/3/
HTML
<!Doctype html>
<body>
<h2>Roll Number</h2>
<img id="dice1" src="http://www.dave-reed.com/book3e/Images/die1.gif">
<img id="dice2" src="http://www.dave-reed.com/book3e/Images/die1.gif">
<p>Enter target number:</p>
<input type="text" id="num"><br><br>
<button id="R">Roll 'em!</button>
<br><br>
<div id="time"></div>
</body>
JavaScript
//define a Dice object, properties and methods
var Dice = {
sides: 6,
rollDie: function(diceElement) {
var rolledValue = Math.floor(Math.random() * this.sides) + 1;
var diceImage = this.getURL(rolledValue);
diceElement.attr("src", diceImage);
},
rollDice: function() {
var diceTotal = 0;
diceTotal += this.rollDie($('#dice1'));
diceTotal += this.rollDie($('#dice2'));
return diceTotal;
},
URL_prefix: "http://dave-reed.com/book3e/Images/",
getURL: function(n) {
//return the URL for an n-dot die
return this.URL_prefix + "die" + n + ".gif";
}
};
//top-level function
function roll_number(n) {
Dice.rollDice();
var die1 = 0;
var die2 = 0;
var numRolls = 0;
do {
die1 = Dice.rollDie($('#dice1'));
die2 = Dice.rollDie($('#dice2'));
numRolls++;
} while(die1 + die2 == n);
return numRolls;
//roll two dice until you hit n
//return the number of rolls
}
function getRoll () {
var number = parseFloat($("#num").val());
var numRolls = roll_number(number);
$("#time").text( "You rolled " + number + " in " + numRolls + " rolls");
}
$(document).ready(function(){
$("#R").on("click", getRoll);
//$("#roll").on("click", Dice.getURL);
});
Thank you again!
-Kron
There's two issues with your code. First die1 and die2 are never set because Dice.rollDie doesn't return a value. Updating the function to return the value of the die fixes this:
rollDie: function(diceElement) {
var rolledValue = Math.floor(Math.random() * this.sides) + 1;
var diceImage = this.getURL(rolledValue);
diceElement.attr("src", diceImage);
return rolledValue;
},
Second, the while loop currently only set to keep running while the sum matches the total, instead it should keep running while it doesn't match the total. It should look like instead:
while(die1 + die2 !== n);
This can lead to infinite loops if you pass a bad value to n (such as null, or anything greater than 12), so be careful
https://jsfiddle.net/0088v6nt/4/
You're setting the counter to zero every time the roll_number function is called i fixed it by moving the counter variable outside the function scope so it's not being reset all the time..
var numRolls = 0;
function roll_number(n) {
Dice.rollDice();
var die1 = 0;
var die2 = 0;
do {
die1 = Dice.rollDie($('#dice1'));
die2 = Dice.rollDie($('#dice2'));
numRolls++;
} while(die1 + die2 == n);
return numRolls;
//roll two dice until you hit n
//return the number of rolls
}
https://jsfiddle.net/0088v6nt/5/

Refresh function per 3 seconds

function random_imglink() {
var myimages = new Array()
//specify random images below. You can have as many as you wish
myimages[1] = "This is text1."
myimages[2] = "This is text2."
myimages[3] = "This is text3."
myimages[4] = "This is text4."
myimages[5] = "This is text5."
myimages[6] = "This is text6."
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.write('<h1 class="comingsoon">' + myimages[ry] + '</h1>')
}
random_imglink()
How do you make it so that the above code gets refreshed every 3 seconds? Like, the output is refreshed every 3 seconds. Thanks.
setInterval is easier way for your query.
Simple Example:
setInterval(function(){ alert("Hello"); }, 3000);
Don't use document.write. Use document.innerHTML instead.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
And of course the setInterval, as the other answers suggest.
I've created a fiddle that I think does what you want.
I hope you like cats.
http://jsfiddle.net/alexjamesbrown/9cu5L666/
Note - I'm setting the inner html of a div, rather than the whole document
function random_imglink() {
var myimages = new Array()
//specify random images below. You can have as many as you wish
myimages[1] = "http://placekitten.com/g/100/400"
myimages[2] = "http://placekitten.com/g/200/250"
myimages[3] = "http://placekitten.com/g/300/234"
myimages[4] = "http://placekitten.com/g/500/300"
myimages[5] = "http://placekitten.com/g/100/400"
myimages[6] = "http://placekitten.com/g/430/100"
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1;
var div = document.getElementById('myContainer');
div.innerHTML='<h1 class="comingsoon"><img src="' + myimages[ry] + '"</img></h1>'
}
setInterval(function(){ random_imglink(); }, 3000);
You can use setInterval
window.setInterval(random_imglink,3000);
You can use
window.setInterval(random_imglink, 3000);
but be cautious because if your browser does not render the content in the time interval you should expect choppiness and dropped frames. A much better approach is to use requestAnimationFrame
The Window.requestAnimationFrame() method tells the browser that you
wish to perform an animation and requests that the browser call a
specified function to update an animation before the next repaint. The
method takes as an argument a callback to be invoked before the
repaint.
function random_imglink() {
var myimages = new Array()
//specify random images below. You can have as many as you wish
myimages[1] = "This is text1."
myimages[2] = "This is text2."
myimages[3] = "This is text3."
myimages[4] = "This is text4."
myimages[5] = "This is text5."
myimages[6] = "This is text6."
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.body.innerHTML = '<h1 class="comingsoon">' + myimages[ry] + '</h1>';
}
window.setInterval(random_imglink, 3000);

JavaScript Click images with button navigation

New to web development and trying to create a gallery of images that cycle through with the click of a "previous" and "next" button. Does anybody know how to do this? I don't think I've done anything right but I'll include what I've done so far. The idea is to make this adaptable to n indefinite number of images.
code:
<img src= "photos/1.jpg" id="currentImage" height="288"/>
<button id= "prev" onclick="prevImage()" class="portfolioNavigation">Previous</button>
<button id= "next" onclick="nextImage()" class="portfolioNavigation">Next</button>
<script type= "text/javascript">
var counter = 2;
var 1 = "photos/1.jpg";
var 2 = "photos/2.jpg";
var 3 = "photos/3.jpg";
prev.onclick = function(){
document.getElementById("currentImage").src = counter - 1;
counter--;
}
next.onclick = function(){
document.getElementById("currentImage").src = counter + 1;
counter++;
}
if(counter == 3){
counter = 0;
};
</script>
There is no need of using "onclick" inside button tags.
<script type= "text/javascript">
var counter = 2;
var sourceUrl = "photos/" + counter + ".jpg";
var prev = document.getElementById("prev");
var next = document.getElementById("next");
prev.onclick = function(){
counter--;
document.getElementById("currentImage").src = sourceUrl;
}
next.onclick = function(){
counter++;
document.getElementById("currentImage").src = sourceUrl; }
if(counter == 3){
counter = 0;
};
</script>
As others have posted, you cannot use an int as a variable name.
You also had "onclick" events on each button and events set via jQuery, you just need one or the other.
Storing each src string in an array and accessing it by using "counter" will work for you. It will also allow you to use a variable amount of images.
HTML
<img src= "photos/1.jpg" id="currentImage" height="288"/>
<button id= "prev" class="portfolioNavigation">Previous</button>
<button id= "next" class="portfolioNavigation">Next</button>
JavaScript
var counter = 0;
var srcArray = ["photos/1.jpg", "photos/2.jpg", "photos/3.jpg"];
prev.onclick = function(){
document.getElementById("currentImage").src = srcArray[--counter];
}
next.onclick = function(){
document.getElementById("currentImage").src = srcArray[++counter];
}
if(counter == 3){
counter = 0;
};
If you inspect the image element in this JSFiddle, you'll see the src updating correctly.
There are couple of issues in your code right now. One of them is that your variables names are plain numbers. You cannot have variable names starting with numbers in JavaScript. Although not a great example, _1 is valid, image1 is a valid and even a more descriptive variable number.
Another issue is, when you are setting the src attribute of currentImage you are also setting that attribute to a value of plain number. That is not a valid image url.
You can put the photo URLs in an array and cycle through those images when next and previous buttons are pressed.
Try something like this (warning untested code):
var images = ["photos/1.jpg", "photos/2.jpg", "photos/3.jpg"];
var numImages = images.length;
prev.onclick = function(){
document.getElementById("currentImage").src = images[(counter - 1) % numImages];
counter--;
}
The significance of the % operator here is that it wraps around the value of [0, numImages).

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