Outputting a random image from an array using JS - javascript

I'm trying to output a random image from my array and then remove it from the array afterwards for a matching game. I'm new to programming in general and I've seen (what I'm sure are) easier ways of doing it but nothing I understand yet so I'm trying it this way. The problem is that I can't get an image to print out and I'm not sure why. Any help would be appreciated! thanks!
HTML
<script>
printImage(); Sites.splice(r,1);
</script>
JS
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'img0.jpg';
...
imgArray[23] = new Image();
imgArray[23].src = 'img23.jpg';
ImageRotation = imgArray.length;
FirstHalf = '<img src="img';
LastHalf = '.jpg" style="width:100px; height: 100px;">';
function printImage() {
var r = Math.ceil(Math.random() * ImageRotation);
document.write(FirstHalf + r + LastHalf);
}

This is how you can do what you are tried to achieve:
I've used setInterval to demonstrate.
Fiddle
HTML:
<img src="http://dummyimage.com/100x100/252799/fff.png&text=one" />
JavaScript:
var imgs = ['http://dummyimage.com/100x100/252799/fff.png&text=one', 'http://dummyimage.com/100x100/252799/fff.png&text=two', 'http://dummyimage.com/100x100/252799/fff.png&text=three', 'http://dummyimage.com/100x100/252799/fff.png&text=four', 'http://dummyimage.com/100x100/252799/fff.png&text=five', 'http://dummyimage.com/100x100/252799/fff.png&text=six', 'http://dummyimage.com/100x100/252799/fff.png&text=seven', 'http://dummyimage.com/100x100/252799/fff.png&text=eight', 'http://dummyimage.com/100x100/252799/fff.png&text=nine', 'http://dummyimage.com/100x100/252799/fff.png&text=ten'];
setInterval(function() {
var im = document.getElementsByTagName('img')[0];
im.src = imgs[Math.round(Math.random() * (imgs.length - 1))];
}, 1000);

Here is another way of setting the image, based on #chipChocolate.py's answer, and addressing OP's requirement that each image is removed from the list. Instead of changing the first image in the HTML, it rewrites the inner HTML within a <div> container.
<html>
<head>
<script type="text/javascript">
var imgs = ['http://dummyimage.com/100x100/252799/fff.png&text=one', 'http://dummyimage.com/100x100/252799/fff.png&text=two', 'http://dummyimage.com/100x100/252799/fff.png&text=three', 'http://dummyimage.com/100x100/252799/fff.png&text=four', 'http://dummyimage.com/100x100/252799/fff.png&text=five', 'http://dummyimage.com/100x100/252799/fff.png&text=six', 'http://dummyimage.com/100x100/252799/fff.png&text=seven', 'http://dummyimage.com/100x100/252799/fff.png&text=eight', 'http://dummyimage.com/100x100/252799/fff.png&text=nine', 'http://dummyimage.com/100x100/252799/fff.png&text=ten'];
var pictures = imgs.length;
var picim =[];
for (var i=0; i<pictures; i++)
picim [i] = i;
var num = 0; // current index of picture number
function randpic() {
if (pictures > 1) {
pictures--;
for (var i=num; i<pictures; i++) // remove current picture index
picim[i] = picim[i+1];
num = Math.floor(Math.random() * pictures);
var content = '<IMG src="' + imgs[picim [num]] + '" />';
document.getElementById('randpic').innerHTML = content;
}
}
</script>
</head>
<body>
<div id="randpic" onClick="javascript:randpic()">
<img src="http://dummyimage.com/100x100/252799/fff.png&text=one" />
</div>
</body>
</html>

Related

Take the array value in order and assign a link to the image

Hello i have some blocks in HTML
<div class="feed_name"><img height="50">
<div class="feed_name"><img height="50">
<div class="feed_name"><img height="50">
<div class="feed_name"><img height="50">
and some code js
var images = ["50.jpg","51.jpg","52.jpg","53.jpg","54.jpg","55.jpg","56.jpg","57.jpg","58.jpg","59.jpg","60.jpg","61.jpg","62.jpg","63.jpg","64.jpg","65.jpg","66.jpg","67.jpg","68.jpg","69.jpg","70.jpg","71.jpg","72.jpg","73.jpg","74.jpg","75.jpg","76.jpg","77.jpg","78.jpg","79.jpg","80.jpg","81.jpg","82.jpg","83.jpg","84.jpg","85.jpg","86.jpg","87.jpg","88.jpg","89.jpg","90.jpg"];
var target = document.getElementsByTagName('img');
var returnImages = [];
var currentImages;
function getUnique(count) {
// Make a copy of the array
var tmp = images.slice(images);
var ret = [];
for (var i = 0; i < count; i++) {
var index = Math.floor(Math.random() * tmp.length);
var removed = tmp.splice(index, 1);
// Since we are only removing one element
ret.push('img/users/' + removed[0]);
$(".feed_name img").each(
$(".feed_name img").attr("src", ret[i])
);
}
return ret;
}
returnImages.push(getUnique(6));
console.log(returnImages);
I want to make all image different form array returnImage but dont know how, pls help
My VanillaJS attempt
/* a simple Array shuffler helper */
var shuffle = function(array) {
var a = array.slice(0);
a.sort(() => Math.random() - 0.5);
return a;
}
/* retrieve all the nodes of the images */
var imagesNode = document.querySelectorAll('.feed_name img');
/* fill an array of integers [50,...,90] */
var imagesUrl = Array(41).fill(0).map((i, j) => j + 50);
/* shuffle the array, limit the length of the array to the length
* of the nodes and - if you need it - sort() it again
*/
var imagesPicked = shuffle(imagesUrl).slice(0, imagesNode.length).sort();
/* set images url */
[...imagesNode].map((node) => {
var num = imagesPicked.shift();
node.src = num + '.jpg';
node.title = "this is the image number " + num;
});
<body>
<div class="feed_name"><img /></div>
<div class="feed_name"><img /></div>
<div class="feed_name"><img /></div>
<div class="feed_name"><img /></div>
</body>
This is a JS way there are way to attach the img tag to the div container.
var items = [imgaddr1, imgaddr2, imgaddr3];
var target = document.querySelector("img-container");
items.forEach(function(item) {
var img = document.createElement("img");
img.src = item;
target.appendChild(img);
});
HTML code
<div id="img-container">
JQuery code
$(items).each(function(key, value) {
$('div#img-container').append("<div><img src='" + value + "' />
</div>");
});

How to set src to each shuffled image in javascript?

I'm trying to shuffle images from array to a specific div.
<body>
<div id="set"></div>
</body>
<script>
var ArrayOfImages = ['bar.jpg',
'foo.jpg',
'koo.jpg',
'too.jpg'
];
var set = document.getElementById("set");
set.addEventListener("click", randomize, false);
ArrayOfImages.forEach(function(image) {
var elem = document.createElement('img');
elem.src = image;
set.appendChild(elem);
});
function shuffle(array) {
let counter = array.length;
// While there are elements in the array`enter code here`
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
function randomize() {
set.innerHTML = shuffle(ArrayOfImages);
}
</script>
Now the problem is, that innerHTML only changes the text of the image but cannot set an src to it. Though it does the shuffle.
Any help would be appreciated!
.innerHTML will change the actual HTML, not the images src which is what you want to change.
At the moment you are getting your image elements from your HTML using
document.getElementById('set)
however, you HTML can only have one element with the id set. Thus, you can use the class attribute instead to give multiple elements the identifier of 'set' and get all your image elements using:
document.getElementsByClassName('set')
which will return a collection of your HTML image tags. Now, to change each image's source you can loop over this collection or loop over your shuffled images and set each image's source.
See an example below for further clarification:
var img_elems = document.getElementsByClassName('set'); // Get all elements to set the image to
// To go into your randomize() function:
// Shuffled images returned via your shuffle() function
var shuffled_images = ['https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350', 'https://www.pandotrip.com/wp-content/uploads/2018/09/Seigantoji-Pagoda-and-Nachi-Falls-in-Nacho-Japan.jpg', 'https://www.elastic.co/assets/bltada7771f270d08f6/enhanced-buzz-1492-1379411828-15.jpg'];
for (var i = 0; i < shuffled_images.length; i++) {
img_elems[i].src = shuffled_images[i]; // Set the image to the src value.
}
/* Ignore this */
img {
height: 200px;
width: 200px;
}
<img src="" class="set" /><br />
<img src="" class="set" /><br />
<img src="" class="set" />
More clean and better way of doing it in vanilla javascript.
The issue was in your shuffle function.
var image_swap_tool = function(options){
var self = this;
self.ArrayOfImages = options.ArrayOfImages;
self.image_container_elem = document.getElementById("set");
self.image_container_elem.addEventListener("click", function(){
self.randomize();
});
}
image_swap_tool.prototype.create_image = function(){
var self = this;
var images = self.ArrayOfImages;
var image_container = self.image_container_elem;
image_container.innerHTML = '';
for(var i=0; i < images.length;i++){
var img = document.createElement('img');
img.setAttribute('src',images[i]);
image_container.appendChild(img);
}
};
image_swap_tool.prototype.shuffle = function(){
var self = this;
var images = self.ArrayOfImages;
let counter = images.length;
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = images[counter];
images[counter] = images[index];
images[index] = temp;
}
//Set new order back to images for next time
self.ArrayOfImages = images;
//Images are shuffled then append them again
self.create_image();
}
image_swap_tool.prototype.randomize = function(){
var self = this;
var image_container = self.image_container_elem;
self.shuffle();
}
var options = {};
options.ArrayOfImages = ['bar.jpg', 'foo.jpg', 'koo.jpg', 'too.jpg'];
var tool = new image_swap_tool(options);
tool.create_image();
Thanks

change HTML code for fading background replacing images

This is my HTML code:
<html>
<head>
<script language="JavaScript">
<!--
// Set speed (milliseconds)
var speed = 4000
// Specify the image files
var Pic = new Array() // don't touch this
// to add more images, just continue
// the pattern, adding to the array below
Pic[0] = 'img_1.jpg'
Pic[1] = 'img_2.jpg'
Pic[2] = 'img_3.jpg'
Pic[3] = 'img_4.jpg'
// =======================================
// do not edit anything below this line
// =======================================
var t
var j = 0
var p = Pic.length
var preLoad = new Array()
for (i = 0; i < p; i++){
preLoad[i] = new Image()
preLoad[i].src = Pic[i]
}
function runBGSlideShow(){
if (document.body){
document.body.background = Pic[j];
j = j + 1
if (j > (p-1)) j=0
t = setTimeout('runBGSlideShow()', speed)
}
}
//-->
</script>
</head>
<body onload="runBGSlideShow()">
</body>
</html>
I tried everything I know to change it so the pictures will fade when replacing but I didn't succeed.
If you can I will appreciate it if you will add to the HTML code (if can't it's ok to add css )
Please look and see if you can help me.
Why reinvent the wheel?
There's a beautiful jQuery plugin that does this already
http://srobbin.com/jquery-plugins/backstretch/

Easy image rotating gallery

I have this image-rotating-script that i cannot get to work in any major browser.
What the JS does is to show a random image on pageload.
Here's my code:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
<!-- Begin
var theImages = new Array();
theImages[0] = 'img/rot/forside/FrontReklame1.jpg';
theImages[1] = 'img/rot/forside/FrontReklame2.jpg';
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('<img src="'+theImages[whichImage]+'" alt="Se vores hingste!" />')
};
// End -->
</script>
What i use to call the image:
<script type="text/javascript">
<!-- Begin
showImage();
// End -->
</script>
This code doesn't show any image live on the net and sometimes it doesn't when i test the page locally?! What am i missing here?
First of all, jquery is not needed in your code.
¿What is the purpose of var j?
Probably you are running showImage() in Header so you can't see the picture.
Try this:
function showImage(){
var selectedImage = preBuffer[whichImage];
selectedImage.alt = "Se vores hingste!";
// Using appendChild instead of document.write
document.body.appendChild(selectedImage);
};

Image swapping hyperlinks

I want to have some hyperlink images that keep changing after a period of time..I have used 2 arrays images and links..2 respective functions execute that change image and links respectively after 2 seconds of time..But I am getting a blank screen as output..I wrote the code as:
<html>
<head>
<title> New Document </title>
</head>
<body>
<img id="img" width="1300" height="200"/>
<link id="link" >
<script type="text/javascript">
var x=0;
var y=0;
var images = new Array();
var links = new Array();
images[0] = "D:\images\31.jpg";
images[1] = "D:\images\32.jpg";
links[0] = "https://www.google.co.in" ;
links[1] = "https://www.facebook.com" ;
function changeImage()
{
document.getElementById("img").src=images[x];
x = (x + 1) % images.length;
}
function changeLinks()
{
document.getElementById("link").href=links[y];
y = (y + 1) % links.length;
}
window.onload = function() {
changeImage();
setInterval(changeImage,2000);
}
window.onload = function() {
changeLinks();
setInterval(changeLinks,2000);
}
</script>
</body>
</html>
Your problem is this:
images[0] = "D:\images\31.jpg";
images[1] = "D:\images\32.jpg";
those are supposed to be hyperlinks, not file paths! Also, the backslash is an escape char in JS, so you need to double it (\\). So try something like:
images[0] = "file:/D:/images/31.jpg";
images[1] = "file:/D:/images/32.jpg";

Categories

Resources