How to display random images from array [duplicate] - javascript

This question already has answers here:
Getting a random value from a JavaScript array
(28 answers)
Closed 5 years ago.
So im creating an app that helps you decide on a movie to watch. one of the functions on the app is a randomizer button which randomly displays a movie based on the genre you selected but not sure how to display the image. heres what i have so far. Thank you!
<body>
<button id='randomBut'>RANDOMIZE</button>
<div id='movieImg'><img src='movie1.svg'></div>
</body
<script>
var randomizer = document.getElementById("randomBut");
var randimg = document.getElementById("movieImg");
var movieimages = ["movie1.svg", "movie2.svg", "movie3.svg"];
document.getElementById("movieImg").innerHTML = movieimages;
randomizer.addEventListener("click", function(){
var randimg = document.createElement("img");
randimg.src = "movieimages" ;
</script>

put the id on the image and then create a random number generator. use that random number and choose the image from the array and assign it to the image src
<button id='randomBut'>RANDOMIZE</button>
<div><img id='movieImg' src='http://placehold.it/100x100'></div>
<script>
var randomizer = document.getElementById("randomBut");
var randimg = document.getElementById("movieImg");
var movieimages = ["http://placehold.it/100x100", "http://placehold.it/150x100", "http://placehold.it/100x150"];
randomizer.addEventListener("click", function(){
var randNum = Math.floor(Math.random() * movieimages.length) + 0
randimg.src = movieimages[randNum] ;
});
</script>

Related

Javascript: why does the image not change in the HTML file

So I am developing a dice program in JavaScript where, when run, if the current die is on 1, it should go to 2. If the die is currently 2 it should go to 3 and so on. At the end of the process, when the die is on 6, it should loop back and go to 1.
However, when it's on 6 and adds 1, it shows 7 which is not there and it shows an error.
Here is my code
var rand = "";
var dice = document.getElementById("dice");
rand = Math.floor(Math.random()*6)+1;
//console.log(rand);
//
var y = 1;
var Totaler = (y+rand);
console.log(Totaler);
var My_Array = [1,2,3,4,5,6];
var link = "https://www.paulneve.com/pp/dice1.png";
var letters = link.slice(-5,33);
dice.src = "https://www.paulneve.com/pp/dice"+My_Array[Totaler]+".png";
<!-- Image1:"https://www.paulneve.com/pp/dice1.png"-->
<!-- Image2:"https://www.paulneve.com/pp/dice2.png"-->
<!-- Image3:"https://www.paulneve.com/pp/dice3.png"-->
<!-- Image4:"https://www.paulneve.com/pp/dice4.png"-->
<!-- Image5:"https://www.paulneve.com/pp/dice5.png"-->
<!-- Image6:"https://www.paulneve.com/pp/dice6.png"-->
<div>You've rolled</div>
<img id="dice" src="https://www.paulneve.com/pp/dice1.png" />
The problem is that you are adding 1 to your random number twice. I've also simplified the code by removing the lookup array, as that's a bit redundant.
var rand = Math.floor(Math.random()*6)+1;
var dice = document.getElementById("dice");
dice.src = "https://www.paulneve.com/pp/dice"+rand+".png";
<!-- Image1:"https://www.paulneve.com/pp/dice1.png"-->
<!-- Image2:"https://www.paulneve.com/pp/dice2.png"-->
<!-- Image3:"https://www.paulneve.com/pp/dice3.png"-->
<!-- Image4:"https://www.paulneve.com/pp/dice4.png"-->
<!-- Image5:"https://www.paulneve.com/pp/dice5.png"-->
<!-- Image6:"https://www.paulneve.com/pp/dice6.png"-->
<div>You've rolled</div>
<img id="dice" src="https://www.paulneve.com/pp/dice1.png" />
Arrays start at 0. So to get the 6th die from your array you need My_Array[5]. To get the 1st die you need My_Array[0]. You need to change your code to only select from 0 to 5:
rand = Math.floor(Math.random()*6);
Also stop adding y+rand and change to:
var Totaler = rand;
That way when you select My_Array[Totaler] it will give you 6 if Totaler = 5. You don't really need My_Array though, you can just use rand+1.

Randomly redirect to url BUT 1 number changes (via Javascript)

So, I use this code
<script type="text/javascript">
var urls = new Array();
urls[0] = "/truth";
urls[1] = "/truth1";
urls[2] = "truth2";
var random = Math.floor(Math.random()*urls.length);
window.location = urls[random];
</script>
and I use "/truth1" "/truth2" "dare1" etc
Is it at all possible to have javascript automatically put a random number at the end of the URL between what I set it to?
In other words
I want Javascript to add a number to the end of
truthordare0.weebly.com/truth
truthordare0.weebly.com/dare
To truthordare0.weebly.com/dare1, truthordare0.weebly.com/dare2
To truthordare0.weebly.com/truth1, truthordare0.weebly.com/truth2
putting a random number between 1-25 at the end of "truth" or "dare". If I have to make the numbers two-digit, please let me know!
It might be handy to know:
-The code above will be used on truthordare0.weebly.com/truth
(which will redirect to /truth1, /truth2, etc
-The code above is used in vitemulti.weebly.com/yesorno-select
Thank you very much!!
<script type="text/javascript">
var urls = new Array();
urls[0] = "/truth";
urls[1] = "/truth1";
urls[2] = "truth2";
var random = Math.floor(Math.random()*urls.length);
window.location = "https://truthordare0.weebly.com/" + urls[random];
</script>

Random Image Display, Without Repeat, with Javascript

I know there are already a few questions like this, but I just can't seem to apply any of the answers (this is my first time making anything like this at all). I currently have a page that, when a button is pushed, a random image appears (thanks to some of the great posts on here, this is actually working). My issue is, the random number has a lot of repeats prior all the images being seen. I am wanting to make it where all images are seen (in a random order) before any duplicates. This is what is in the body:
<form name="imageForm">
<table border=3>
<tr align="center">
<td>
<input onclick="displayImage();" type=button value="Click Here">
</td>
</tr>
<tr>
<td>
<img src="blank.jpg" name="canvas" />
</td>
</tr>
</table>
</form>
Here is the script:
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
document.canvas.src = imagesArray[num];
}
</script>
From what I have read, the way to do this would be to add a spice, and have shown images dropped into a new array, then once the original array equals 0, then have it reset. Try as I might, I have not been able to successfully integrate that into my code :( . This is what I ended up with (which does nothing, and breaks the function entirely):
<script>
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var shownImages = []
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
document.canvas.src = imagesArray[num];
shownImages.unshift(imagesArray.splice(num,num+1));
if(images.length == 0){
images.Array = shownImages;
shownImages = [];
return shownImages[0];
}
</script>
Another method mentioned seemed to be to have a function that shuffled the images first, then displayed them in the shuffled order, then reshuffled and repeated, but I got even less far with that.
There also seems to be some question on whether the random number max should be imagesArray.length by itself, or +1 or -1. I am sure there are a number of other issues with this as well, but like I said, this is my first attempt. Any help is appreciated.
You should keep track of the numbers that you have generated, and if its a repeat then get a new number.
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var usedImages = {};
var usedImagesCount = 0;
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
</script>

getElementById() .innerHTML/.src

I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great
Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>

how to change the image when a page is refreshed using JavaScript?

I want to change the image when the page is refresh using html. I place my partial code here. i want a script or anything do change the image when the page gets refresh.. Please help me to do this using html ...
<div class="one-image">
<a href="">
<img src="img/IMG_1035.jpg" class="giThumbnail" alt="Nightclubs"></a><h4 class="giDescription">
Nightclubs</h4>
</div>
the above image tag image is change every refresh.. please help me ..
I believe this would work, but all your images would have to be sequentially named, e.g. 1-100. Also note that the script was placed AFTER the IMG tag.
<div class="one-image">
<a href="">
<img id="imgRand" src="" class="giThumbnail" alt="Nightclubs">
</a>
<h4 class="giDescription">
Nightclubs
</h4>
</div>
<script language="javascript">
// random number between 1 and 100
var numRand = Math.floor(Math.random()*101);
document.getElementById("imgRand").src = "img/IMG_"+numRand+".jpg";
</script>
The random formula in JS is:
var random = Math.floor(Math.random() * (max - min + 1)) + min;
so if you only had 5 images between 135 and 140 your script would look like:
var random = Math.floor(Math.random() * (140 - 135 + 1)) + 135;
If you wanted to change the image client-side, like a slideshow, just add a timer.
<script language="javascript">
function setImg(){
// random number between 1 and 100
var numRand = Math.floor(Math.random()*101);
document.getElementById("imgRand").src = "img/IMG_"+numRand+".jpg";}
// call it the first time
setImg();
// set an interval to change it every 30 seconds
window.setInterval("setImg()",30000);
</script>
Not Tested but something like this should work using Javascript:
//Add following inside script tag
//Add id to your image tag
var theImages = new Array();
theImages[0] = 'images/first.gif' // replace with names of images
theImages[1] = 'images/second.gif' // replace with names of images
theImages[2] = 'images/third.gif' // replace with names of images
......
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.getElementById("yourImgTagId").src = theImages[whichImage];
}
//call the function
showImage();
Did you mean something like that
What type of server are you using? Using PHP or ASP you can accomplish this using a script that cycles through your images in a script. So your HTML would just point to the script instead of directly to an image:
<img src="image_rotation_script.php" class="giThumbnail" alt="Nightclubs">
Then your script would rotate through your various images. Here is a PHP example:
<?php
header('content-type: image/jpeg');
// Your own logic here to pull from a database, randomize an array of images etc.
$images = array('img/IMG_1.jpg','img/IMG_2.jpg','img/IMG_3.jpg');
$imageFile = array_rand($images);
$image = imagecreatefromjpeg($imageFile);
imagejpeg($image);
imagedestroy($image);
?>
Use can use JavaScript to change the src field of the image tag. First insert an ID attribute to your img tag, or a NAME attribute if it appears more often on the same page.
<img id="nightClubImage" src="img/IMG_1035.jpg" class="giThumbnail" alt="Nightclubs">
Then write a script and change the src field:
document.getElementById('nightClubImage').src = "newImage.jpg";
If you want use only client-side solution try this:
<img src="img/IMG_1035.jpg" class="giThumbnail" alt="Nightclubs">
<script type="text/javascript">
var images = ['img/IMG_1035.jpg', 'img/IMG_1036.jpg', 'img/IMG_1037.jpg'];
document.getElementById('gitThumbnail').src = images[Math.round((Math.random() * (images.length-1))];
</script>

Categories