Trying to display random javascript images in separate DIVs - javascript

I have working javascript code that produces multiple random images in to one div.
I have tried a few attempts to display each random image in a separate div but with no luck. I got "close" but no success.
Here is working code:
<head>
<style>
.onetwothreefour {
width: 25%;
display: inline-block;
}
</style>
<script>
function displayNow() {
var images = ["00.png","01.png","02.png","03.png","04.png","05.png","06.png"];
var selectedIndices = []
while (selectedIndices.length < 4) {
var index = images[Math.floor(Math.random() * images.length)]
if (selectedIndices.indexOf(index) == -1) {
selectedIndices.push(index)
}
}
for (i = 0; i < selectedIndices.length; i++) {
var img = document.createElement("img");
img.src = "imagesfolder/" + selectedIndices[i]
img.className = "onetwothreefour"
var src = document.getElementById("images");
src.appendChild(img);
}
}
</script>
</head>
<body onLoad="displayNow();">
<div id="images"><!-- Images --></div>
<!-- the above works fine but I would like the result below -->
<div class="container"><div class="row">
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
</div></div>
</body>
Note: I have jquery and bootstrap loaded.
I appreciate any help.

Explaination : The while loop runs for four times. A random index is generated, and the element is removed from images array, and pushed into selectedIndices array. By this way, no iteration will be wasted, as each time, a unique image will be generated. I have used forEach loop, which iterates over all the elements of selectedIndices array.
NOTE : The comment inside the forEach loop is a one line way to do so. However, using innerHTML is not appreciated sometimes.
function displayNow() {
var images = ["00.png", "01.png", "02.png", "03.png", "04.png", "05.png", "06.png"];
var selectedIndices = [];
var src = document.getElementById("images");
while (selectedIndices.length < 4) {
let index = Math.floor(Math.random() * images.length);
let img = images.splice(index, 1)[0];
selectedIndices.push(img)
}
selectedIndices.forEach((el) => {
let img = new Image();
img.src = "imagesfolder/" + el;
img.alt = el;
img.className = "onetwothreefour";
let imgCont = document.createElement("div");
imgCont.append(img);
src.append(imgCont);
// src.innerHTML += "<div><img class='onetwothreefour' src='imagesfolder/" + el + "' alt='" + el + "'></div>";
});
}
.onetwothreefour {
width: 25%;
display: inline-block;
}
<body onLoad="displayNow();">
<div id="images"></div>
<div class="container">
<div class="row">
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
</div>
</div>
</body>

You're already using createElement() to build the img elements - you can use the same method to create a new div, add the child img to it, then append that to the DOM. Try this:
function displayNow() {
var src = document.getElementById("images");
var images = ["00.png", "01.png", "02.png", "03.png", "04.png", "05.png", "06.png"];
var selectedIndices = []
while (selectedIndices.length < 4) {
var index = images[Math.floor(Math.random() * images.length)]
if (selectedIndices.indexOf(index) == -1) {
selectedIndices.push(index)
}
}
for (i = 0; i < selectedIndices.length; i++) {
var img = document.createElement("img");
img.src = "imagesfolder/" + selectedIndices[i]
img.className = "onetwothreefour";
img.title = selectedIndices[i]; // just for this demo
var div = document.createElement('div');
div.append(img);
src.append(div);
}
}
.onetwothreefour {
width: 25%;
display: inline-block;
}
<body onLoad="displayNow();">
<div id="images">
<!-- Images -->
</div>
<!-- the above works fine but I would like the result below -->
<div class="container">
<div class="row">
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
</div>
</div>
</body>

Related

Need to upload multiple image on existing grid and also delete the image using jquery

I have six boxes. In this box already have dummy image.I need to upload image and that placed to the top box one by one and need to delete also.
When we upload image using upload button, that placed on above div one by one. Currently when i try to add image that placed to all the six divs.
<div class="image-wrapper" style="display:flex;">
<div class="image-wrap">
<img id="img_0" src="assets/images/img1.jpg" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_1" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_2" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_3" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_4" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_5" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
</div>
<div class="upload-btn">
<div class="upload-btn-wrapper">
<button class="btn">Upload a file1</button>
<input type="file" id="files" name="files[]" multiple="">
</div>
</div>
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<div><span class=\"pip image-wrap\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">X</span>" +
"</span></div>").insertAfter(".image-wrap");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
You are using generic selector (".image-wrap") hence image getting added to all div. You can access divs with index 0... n using eq() method and maintain last index in a variable so that you can calculate next index and add next image to the div.
No need to add remove button click handler each time when file loaded as this will cause issue and you will end with multiple click handler. Better, put it outside using .on() so that dynamically added remove buttons will work.
See below code
$(document).ready(function() {
var imageIndex = 0; // variable to save index
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<div><span class=\"pip image-wrap\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result
+ "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">X</span>" +
"</span></div>").insertAfter(".image-wrap:eq(" + imageIndex + ")"); // use index
imageIndex++; // increment index by 1
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
// put remove action here for dynamically added image
$(document).on("click",".remove",function(){
$(this).parent(".pip").remove();
});
});
Just because you are using a class selector with insertAfter its adding the image after every div having class .image-wrap instead use below code. Use the last() function to get the last .image-wrap and append it to that element. Below is a sample code.
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
});
} else {
alert("Your browser doesn't support to File API")
}
});
function uploadFile() {
var files = $('#files')[0].files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
var emptyImg = $('img.img-fluid:not(.hasImage)');
emptyImg[0].src = e.target.result;
$(emptyImg[0]).addClass('hasImage');
$(".remove").click(function() {
var img = $(this).parent().find('img.hasImage')[0];
img.src = '';
$(img).removeClass('hasImage');
});
});
fileReader.readAsDataURL(f);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="image-wrapper" style="display:flex;">
<div class="image-wrap">
<img width="100" id="img_0" src="assets/images/img1.jpg" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_1" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_2" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_3" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_4" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_5" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
</div>
<div class="upload-btn">
<div class="upload-btn-wrapper">
<button class="btn" onclick="uploadFile()">Upload a file1</button>
<input type="file" id="files" name="files[]" multiple="">
</div>
</div>
Hope this helps :)

Display random images in a fixed position

I have 3 images. What i want to do is when i click on any one of the image a random image should be displayed on a div.
Here is the code. Help please.
var iarr=["1.jpg","2.jpg","3.jpg"];
function select()
{
var random=Math.floor(Math.Random()*3);
document.getElementById('disp').innerHTML = iarr[random];
}
<html>
<body>
<h4> MAKE A CHOICE </h3>
<img id='x' onclick="select" src='1.jpg'/>
<img id='y' onclick="select" src='2.jpg'/>
<img id='z' onclick="select" src='3.jpg'/>
<div id='disp'/>
var iarr=["1.jpg","2.jpg","3.jpg"];
function select(){
var random = Math.floor(Math.random() * iarr.length);
var div = document.getElementById('disp');
var image = "<img src=\"" + iarr[random] + "\"/>";
div.innerHTML = image;
}
<html>
<body>
<h4> MAKE A CHOICE </h4>
<img id='x' onclick="select()" src='1.jpg'/>
<img id='y' onclick="select()" src='2.jpg'/>
<img id='z' onclick="select()" src='3.jpg'/>
<div id='disp'/>
Working example: https://jsfiddle.net/pndtdt7t/
var iarr = [
"http://www.wallpapers-for-desktop.com/desktopbilder_for_free/free_desktopbild.jpg",
"http://wikiin.com/media/images/15/04/21/cfe0fdfb23.jpg",
"http://data.whicdn.com/images/89382997/large.jpg"
];
function select() {
var img = "<img src=\""+iarr[Math.floor(Math.random() * iarr.length)]+ "\" />";
document.getElementById('disp').innerHTML = img;
}
<html>
<body>
<h4> MAKE A CHOICE </h3>
<img id='x' onclick="select()" src='1.jpg'/>
<img id='y' onclick="select()" src='2.jpg'/>
<img id='z' onclick="select()" src='3.jpg'/>
<div id='disp'/>

Change slider's next and previous button to be previews of upcoming or previous pictures

Hey so i have a slider and i need to change the next and previous button backgrounds to show a preview of the next and previous slide. I don't know if it's possible without jQuery but since i'm working on an all javascript slider i'd very much appreciate a javascript solution
This is the HTML
<body onload="Load()"
<div class="container">
<div class="slider">
<div class="slides" id="slide1">
<img src="img/1.jpg">
</div>
<div class="slides" id="slide2">
<img src="img/2.jpg">
</div>
<div class="slides" id="slide3">
<img src="img/3.jpg">
</div>
</div>
<div class="ctrl">
<div class="prev">
<input type="button" onClick="prev();">
</div>
<div class="next">
<input type="button" onClick="next();">
</div>
</div>
</div>
</body>
And the Javascript
nrSlide=3;
function Load(){
nrShown = 0;
vect = new Array(nrSlide + 1);
vect[0] = document.getElementById("slide1");
vect[0].style.visibility = "visible";
for (var i = 1; i < nrSlide; i++)
{
vect[i] = document.getElementById("slide" + (i+1));
}
}
function next(){
nrShown++;
if(nrShown == nrSlide) {
nrShown=0;
}
Effect();
}
function prev(){
nrShown--;
if(nrShown == -1) {
nrShown = nrSlide -1;
}
Effect();
}
// Effect
function Effect(){
for (var i=0; i < nrSlide; i++){
vect[i].style.opacity = "0";
vect[i].style.visibility = "hidden";
}
vect[nrShown].style.opacity = "1";
vect[nrShown].style.visibility = "visible";
}
PS: I do realize that this is doable in jQuery but i need a javascript solution. And if you are going to downvot at least leave a reason
nrSlide=3;
function Load(){
nrShown = 0;
vect = new Array(nrSlide + 1);
vect[0] = document.getElementById("slide1");
vect[0].style.visibility = "visible";
for (var i = 1; i < nrSlide; i++)
{
vect[i] = document.getElementById("slide" + (i+1));
}
ShowNextPrev(nrShown);
}
function next(){
nrShown++;
if(nrShown == nrSlide) {
nrShown=0;
}
ShowNextPrev(nrShown);
Effect();
}
function prev(){
nrShown--;
if(nrShown == -1) {
nrShown = nrSlide -1;
}
ShowNextPrev(nrShown);
Effect();
}
function ShowNextPrev(nrShown)
{
var nrShown2 = nrShown == nrSlide-1 ? -1 : nrShown;
document.querySelector(".next").querySelector("input").style.backgroundImage = "url("+document.querySelector(".slider").querySelectorAll("img")[nrShown2+1].src+")";
document.querySelector(".next").querySelector("input").style.backgroundSize = "contain";
var nrShown3 = nrShown == 0 ? nrSlide : nrShown;
document.querySelector(".prev").querySelector("input").style.backgroundImage = "url("+document.querySelector(".slider").querySelectorAll("img")[nrShown3-1].src+")";
document.querySelector(".prev").querySelector("input").style.backgroundSize = "contain";
}
// Effect
function Effect(){
for (var i=0; i < nrSlide; i++){
vect[i].style.opacity = "0";
vect[i].style.visibility = "hidden";
}
vect[nrShown].style.opacity = "1";
vect[nrShown].style.visibility = "visible";
}
Load();
.ctrl > div {
display: inline-block;
}
.slides > img {
height: 40px;
}
<div class="slider">
<div class="ctrl">
<div class="prev">
<input type="button" onClick="prev();">
</div>
<div class="next">
<input type="button" onClick="next();">
</div>
</div>
<div class="slides" id="slide1">
<img src="https://lh6.googleusercontent.com/-Ze9FLpwZjdE/AAAAAAAAAAI/AAAAAAAAAA8/YOtXVkTZpNs/photo.jpg">
</div>
<div class="slides" id="slide2">
<img src="http://icons.iconarchive.com/icons/femfoyou/angry-birds/256/angry-bird-green-icon.png">
</div>
<div class="slides" id="slide3">
<img src="http://icons.iconarchive.com/icons/femfoyou/angry-birds/256/angry-bird-black-icon.png">
</div>
</div>
</div>
This approach should do it. In plain JavaScript using querySelector() and querySelectorAll. You just need the code. The CSS and HTML are just altered to make it work for the example.

Changing all images on timer with JS

I have this 3x3 img gallery. I need all of them to change every certain time with JS.
So far I managed to do this to one of the images. I don't know how to target them all.
<script>
var images = ["http://lorempixel.com/250/200/", "http://lorempixel.com/250/150/"];
var i = 0;
var renew = setInterval(function(){
if(images.length == i){
i = 0;
}
else {
document.getElementByClassName('galleryItem').src = images[i];
i++;
}
},1000);
</script>
<div class="galleryWrapper">
<div class="galleryItem item1">
<img id="image1" src="http://lorempixel.com/250/200/" alt="picture1">
</div>
<div class="galleryItem item2">
<img id="image2" src="http://lorempixel.com/250/200/" alt="picture2">
</div>
<div class="galleryItem item3">
<img id="image3" src="http://lorempixel.com/250/200/" alt="picture3">
</div>
<div class="galleryItem item4">
<img id="image4" src="http://lorempixel.com/250/200/" alt="picture4">
</div>
<div class="galleryItem item5">
<img id="image5" src="http://lorempixel.com/250/200/" alt="picture5">
</div>
<div class="galleryItem item6">
<img id="image6" src="http://lorempixel.com/250/200/" alt="picture6">
</div>
<div class="galleryItem item7">
<img id="image7" src="http://lorempixel.com/250/200/" alt="picture7">
</div>
<div class="galleryItem item8">
<img id="image8" src="http://lorempixel.com/250/200/" alt="picture8">
</div>
<div class="galleryItem item9">
<img id="image9" src="http://lorempixel.com/250/200/" alt="picture9">
</div>
</div>
I don't know JS at all so don't be too harsh.
Thanks in advance.
Remove the onload from your body element (Using DOMContentLoaded event instead it is less intrusive).
var imageList = ["http://lorempixel.com/250/200/", "http://lorempixel.com/250/150/"],
imageListCounter = 0,
imageEls;
function swapImages() {
var i = 0, len = imageEls.length;
for (i = 0; i < len; i++) {
imageEls[i].src = imageList[imageListCounter];
}
imageListCounter++;
if (imageListCounter > imageList.length - 1) {
imageListCounter = 0;
}
}
document.addEventListener('DOMContentLoaded', function(event) {
imageEls = document.querySelectorAll('.galleryItem img');
setInterval(swapImages, 1000);
});
What we are doing here is:
on document ready store all the image elements in imageEls
then start a timer, calling swapImages every 1 second
swapImages iterates over images and changes the .src to what is in the next one in imageList
when the imageListCounter reaches the end of imageList it resets to 0
So the complete html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Gallery</title>
<link rel="stylesheet" href="style.css">
<script>
var imageList = ["http://lorempixel.com/250/200/", "http://lorempixel.com/250/150/"],
imageListCounter = 0,
imageEls;
function swapImages() {
var i = 0, len = imageEls.length;
for (i = 0; i < len; i++) {
imageEls[i].src = imageList[imageListCounter];
}
imageListCounter++;
if (imageListCounter > imageList.length - 1) {
imageListCounter = 0;
}
}
document.addEventListener('DOMContentLoaded', function(event) {
imageEls = document.querySelectorAll('.galleryItem img');
setInterval(swapImages, 1000);
});
</script>
</head>
<body>
<div class="galleryWrapper">
<div class="galleryItem item1">
<img src="http://lorempixel.com/250/200/" alt="picture1">
</div>
<div class="galleryItem item2">
<img src="http://lorempixel.com/250/200/" alt="picture2">
</div>
<div class="galleryItem item3">
<img src="http://lorempixel.com/250/200/" alt="picture3">
</div>
<div class="galleryItem item4">
<img src="http://lorempixel.com/250/200/" alt="picture4">
</div>
<div class="galleryItem item5">
<img src="http://lorempixel.com/250/200/" alt="picture5">
</div>
<div class="galleryItem item6">
<img src="http://lorempixel.com/250/200/" alt="picture6">
</div>
<div class="galleryItem item7">
<img src="http://lorempixel.com/250/200/" alt="picture7">
</div>
<div class="galleryItem item8">
<img src="http://lorempixel.com/250/200/" alt="picture8">
</div>
<div class="galleryItem item9">
<img src="http://lorempixel.com/250/200/" alt="picture9">
</div>
</div>
</body>
</html>
Where you set the image name to image1, you can just change to 'image'+i+''
document.getElementById('image'+i+'').src = images[i];
for (var e = 1; e < 10; e++)
{
var ImgID = 'image' + e;
document.getElementById(ImgID).src = images[i];
}
If you were using jquery you could just do a foreach on all the img elements. but the above will work. if you have 9 images with the ID of image1, image2, image3... you get the idea.
write this code in your else block
var imgs = document.getElementsByTagName('img');
for(j=0;j<imgs.length;j++){
imgs[j].src = images[i];
}
i++;
instead of this
document.getElementByClassName('gallery').src = images[i];
i++;
Give all your images a class attribute with the same value.
assuming you use the value "imagetags", replace your document.getElementById() line with the following:
var elements = document.GetElementsByClassName("imagetags");
for (var elem in elements){
elements[elem].src = images[i];
}

how to create generic html with javascript

I have the following html:
<div id="prog" class="downloads clearfix">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label id="pr1"></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a id="pdfdocument" class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
I want build HTML which is inside the <div id="prog"> with Javascript:
<div id="prog" class="downloads clearfix"></div>
I'm trying to use this Javascript, but without success:
var tmpDocument, tmpAnchorTagPdf, tmpAnchorTagXls, parentContainer, i;
parentContainer = document.getElementById('prog');
for (i = 0; i < documents.length; i++) {
tmpDocument = documents[i];
tmpAnchorTagPdf = document.createElement('a id="pdfdocument" ');
tmpAnchorTagPdf.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagPdf.innerHTML = 'start Download';
tmpAnchorTagXls = document.createElement('a');
tmpAnchorTagXls.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagXls.innerHTML = 'start Download';
parentContainer.appendChild(tmpAnchorTagPdf);
parentContainer.appendChild(tmpAnchorTagXls);
}
If this is a section of code that you will be using more than once, you could take the following approach.
Here is the original div without the code you want to create:
<div id="prog" class="downloads clearfix">
</div>
Create a template in a hidden div like:
<div id="itemtemplate" style="display: none;">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
Then duplicate it with jquery (OP originally had a jquery tag; see below for JS), update some HTML in the duplicated div, then add it to the document
function addItem() {
var item = $("#itemtemplate div.item").clone();
//then you can search inside the item
//let's set the id of the "a" back to what it was in your example
item.find("div.link a").attr("id", "pdfdocument");
//...the id of the label
item.find("div.title label").attr("id", "pr1");
//then add the objects to the #prog div
$("#prog").append(item);
}
update
Here is the same addItem() function for this example using pure Javascript:
function JSaddItem() {
//get the template
var template = document.getElementById("itemtemplate");
//get the starting item
var tempitem = template.firstChild;
while(tempitem != null && tempitem.nodeName != "DIV") {
tempitem = tempitem.nextSibling;
}
if (tempitem == null) return;
//clone the item
var item = tempitem.cloneNode(true);
//update the id of the link
var a = item.querySelector(".link > a");
a.id = "pdfdocument";
//update the id of the label
var l = item.querySelector(".title > label");
l.id = "pr1";
//get the prog div
var prog = document.getElementById("prog");
//append the new div
prog.appendChild(item);
}
I put together a JSFiddle with both approaches here.

Categories