I couldn't display random images without duplicates - javascript

hi i'm working on a task which will display random images. The code that i have shows random images but actually i want to display random images without duplicates. How to get this done. Help me. Thanks in advance.
var images = ['https://cdn.paperindex.com/banner/advertisement/1.jpeg', 'https://cdn.paperindex.com/banner/advertisement/2.jpeg', 'https://cdn.paperindex.com/banner/advertisement/3.jpeg', 'https://cdn.paperindex.com/banner/advertisement/4.jpeg'];
var imagesused = [];
$('.advertisement div').each(function() {
var rand = Math.floor(Math.random() * images.length);
$(this).append('<img src="' + images[rand] + '"/>');
if (imagesused.indexOf(images[rand]) != -1) images.splice(rand, 1);
else imagesused.push(images[rand]);
});
.advertisement div img {
width: 100px;
height: 100px;
margin-right: 10px;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="advertisement">
<div></div>
<div></div>
<div></div>
<div></div>
</div>

Make a copy of original array. And after adding the random image remove it from copy of array.You don't need to create imagesUsed as you removing it from the array.
var images = ['https://cdn.paperindex.com/banner/advertisement/1.jpeg', 'https://cdn.paperindex.com/banner/advertisement/2.jpeg', 'https://cdn.paperindex.com/banner/advertisement/3.jpeg', 'https://cdn.paperindex.com/banner/advertisement/4.jpeg'];
//making copy of original array.
var tempImgs = images.slice(0)
$('.advertisement div').each(function() {
var rand = Math.floor(Math.random() * tempImgs.length);
$(this).append('<img src="' + tempImgs[rand] + '"/>');
tempImgs.splice(rand, 1);
});
.advertisement div img {
width: 100px;
height: 100px;
margin-right: 10px;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="advertisement">
<div></div>
<div></div>
<div></div>
<div></div>
</div>

My approach would be like this, this way is can randomize them no matter how small or big your array is
first create a method which shuffle them
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
and then you use it before looping your array
images = shuffle(images);
var images = ['https://cdn.paperindex.com/banner/advertisement/1.jpeg', 'https://cdn.paperindex.com/banner/advertisement/2.jpeg', 'https://cdn.paperindex.com/banner/advertisement/3.jpeg', 'https://cdn.paperindex.com/banner/advertisement/4.jpeg'];
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
images = shuffle(images);
var imagesused = [];
$('.advertisement div').each(function(x) {
$(this).append('<img src="' + images[x] + '"/>');
});
.advertisement div img {
width: 100px;
height: 100px;
margin-right: 10px;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="advertisement">
<div></div>
<div></div>
<div></div>
<div></div>
</div>

Related

How to repeat randomised img endlessly on javascript?

I have a function that render random image without repeating, but it stops working when the array of images has come to an end, my goal is to restart function with another random order of images, so function can work infinite. I've read another questions, but didn't find something appropriate to me case.
Here is html part:
<div class="card">
<div class="front" onClick="pickimg();return false;"><img
src="1.jpg" alt=""></div>
<div class="back"><img src="2.jpg" name="randimg"></div>
</div>
Css (just in case):
.card {
width: 200px;
height: 300px;
position: relative;
perspective: 1000px;
cursor: pointer;
margin: 0 50px;
}
.front, .back {
width: 100%;
height: 100%;
position: absolute;
display: flex;
justify-content: center;
align-items: center;
transition: 1s;
backface-visibility: hidden;
border-radius: 10px;
}
.front {
transform: rotateY(360deg);
}
.back {
transform: rotateY(180deg);
}
And JS:
var cards = document.querySelectorAll('.card')
Array.from(cards).forEach(function(card) {
card.addEventListener('click', function() {
Array.from(card.querySelectorAll('.back, .front')).forEach(function(el) {
['back', 'front'].forEach(function(s) {
el.classList.toggle(s)
});
});
});
});
var usedImages = {};
var usedImagesCount = 0;
function pickimg(){
var imagenumber = 3;
var randomnumber = Math.random();
var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
images = new Array();
images[0] = "";
images[1] = "3.jpg";
images[2] = "4.jpg";
images[3] = "2.jpg";
var image = images[rand1];
if (!usedImages[rand1]){
document.randimg.src = images[rand1];
usedImages[rand1] = true;
usedImagesCount++;
if (usedImagesCount === images.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
pickimg();
}
}
Thank you for your help.
You could try something like this:
let img = [1,2,3,4,5];
function switchImage () {
for(; ; ){
let x = Math.random() * 10;
if(typeof img[Math.round(x)] !== 'undefined') {
img.splice(x, 1);
break;
}
}
console.log(img);
if (img.length > 0){
setTimeout(() => switchImage (),1000);
}
}
switchImage();
This is a simplified example where every second the function calls itself again and a new image is picked from the image array. The old image is cut out of the array and the function will stop calling itself when every picture is shown.
Try this -
int lastIndex = Math.round(Math.random()*(imagenumber - 1)) + 1;
function pickImg(){
let imagenumber = 3;
int currIndex = Math.round(Math.random()*(imagenumber - 1)) + 1;
images = new Array();
images[0] = "2.jpg";
images[1] = "3.jpg";
images[2] = "4.jpg";
if (lastIndex !== currIndex) {
document.randimg.src = images[currIndex];
lastIndex = currIndex;
}
else {
pickImg();
}
}
If you didn't get any image displayed that means you have to deal with when images[index] returns undefined.
Inshort you need to have index in images always equal to some value.
How about simple like this does this work for you? at least it will not give you same number a row
var imgArr = [1, 2, 3, 4, 5, 6] // imagine this is your img
var lastImgIndex;
function loadImg() {
var RandomIndex = Math.floor((Math.random() * imgArr.length) + 1);
if (lastImgIndex != RandomIndex) {
$('span').text(RandomIndex + ' index of img show');
lastImgIndex = RandomIndex;
} else {
loadImg();
}
}
loadImg();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>

two dimensional array random generator jQuery

All rows always have same numbers, why? They should take random number to populate it. Also, how can I repair it? Once I saw answer here but now I cannot find it.
var mapSizex = 5;
var mapSizey = 6;
var mapArray = [];
$(function() {
console.log("ready!");
$('#map-draw').html(drawMap());
});
function mapGenerator() {
for (i = 0; i < mapSizex; i++) {
for (x = 0; x < mapSizey; x++) {
mapArray[i, x] = getRandom(1, 5);
}
}
}
function drawMap() {
mapGenerator();
var map = '';
tileID = 0;
for (i = 0; i < mapSizex; i++) {
map = map + '<br style="clear: both;">';
for (x = 0; x < mapSizey; x++) {
map = map + '<div class="tile tileID' + tileID + '">' + mapArray[i, x] + '</div>';
tileID++;
}
}
return map;
}
function getRandom(min, max) {
var x = Math.floor((Math.random() * max) + min);
return x;
}
.tile {
float: left;
height: 20px;
width: 20px;
border: 1px solid black;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="map-container">
<div id="map-draw"></div>
</div>
</div>
To post it I need to add some more content but all included information's should be enough to find what I mean.
here is a link to JSFIDDLE woking code
It should be mapArray[i][x] and I added mapArray[i]=[]; in the outer loop.
here is your fixed code:
var mapSizex=5;
var mapSizey=6;
var mapArray=[];
$(function() {
console.log( "ready!" );
$('#map-draw').html(drawMap());
});
function mapGenerator(){
for(i=0;i<mapSizex;i++){
mapArray[i]=[];
for(x=0;x<mapSizey;x++){
mapArray[i][x]= getRandom(1,5);
console.log(i,x,getRandom(1,5))
}
}
}
function drawMap(){
mapGenerator();
console.log(mapArray)
var map='';
tileID=0;
for(i=0;i<mapSizex;i++){
map=map+'<br style="clear: both;">';
for(x=0;x<mapSizey;x++){
map=map+'<div class="tile tileID'+tileID+'">'+mapArray[i][x]+'</div>';
tileID++;
}
}return map;
}
function getRandom(min,max) {
var x = Math.floor((Math.random() * max) + min);
return x;
}

using jQuery to append div's and each div has a different ID

So I'm trying to to use jQuery to append a div which will generate a card using the assigned class. The problem is I need to create a different ID each time so I can put random number on the card. I'm sure there's an easier way to do this. So i'm posing two questions. how to make the code where it put the random number on the card go endlessly. and how to append divs with unique ID's. Sorry if my code isn't the best. It's my first project.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<title></title>
<style>
.cardLook {
border: 1px solid black;
width: 120px;
height: 220px;
border-radius: 5px;
float: left;
margin: 20px;
padding: 5px;
background-color: #fff;
}
#card1,#card2,#card3,#card4,#card5 {
transform:rotate(180deg);
}
#cardTable {
background-color: green;
height: 270px
}
.reset {
clear: both;
}
</style>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<button id="deal">Deal</button>
<button id="hit">hit</button>
<button id="stand">Stand</button>
<button id="hi">hi</button>
<div id="number"></div>
<div id="arrayOutput"></div>
<div id="someId"></div>
<div id="out2"></div>
<div id="cardTable">
</div>
<div class="reset"></div>
<script>
var what;
//Services helper functon
document.getElementById('deal').onclick = function deal() {
var score1 = Math.floor(Math.random() *10 + 1);
var score2 = Math.floor(Math.random() *10 + 1);
var firstCard = score1;
var secondCard = score2;
//myNumberArray.push(firstCard, score2);
//card1.innerHTML = myNumberArray[0];
//card2.innerHTML = myNumberArray[1];
$("#deal").click(function(){
$("#cardTable").append("<div class='cardLook' id='card1'></div>");
});
console.log(score2, score1)
}
var myNumberArray = [];
$("#hit").click(function(){
$("#cardTable").append("<div class='cardLook' id="uniqueIdNumberOne"></div>");
if (myNumberArray > 1) {
#cardTable
}
var card = Math.floor(Math.random() * 10) + 1;
document.getElementById('number').innerHTML=card;
myNumberArray.push(card);
var number = myNumberArray.value;
var arrayOutput = document.getElementById('number');
var someId = document.getElementById('someId');
someId.innerHTML = myNumberArray;
card1.innerHTML = myNumberArray[0];
card2.innerHTML = myNumberArray[1];
card3.innerHTML = myNumberArray[2];
card4.innerHTML = myNumberArray[3];
card5.innerHTML = myNumberArray[4];
// console.log("myNumberArray: ", myNumberArray);
what = calcTotal(myNumberArray);
showMe(calcTotal(myNumberArray));
});
//var output = myNumberArray = calcTotal(list);
function calcTotal(myNumberArray) {
var total = 0;
for(var i = 0; i < myNumberArray.length; i++){
total += myNumberArray[i];
}
return total;
}
//document.getElementById('out2').innerHTML = out2;
console.log("myNumberArray: ", myNumberArray);
function showMe(VAL) {
var parent = document.getElementById('out2');
parent.innerHTML = VAL;
if (calcTotal(myNumberArray) > 21) {
alert('you lose');
}
};
document.getElementById('stand').onclick = function stand() {
var compterDeal1 = Math.floor(Math.random() *10 + 1);
var computerCards = compterDeal1;
console.log(computerCards);
computerArray.push(computerCards);
if (computerCards < 21) {
stand();
}
}
var computerArray = [];
</script>
</body>
</html>
Use an unique class with all of then, and call then by class
Add a global integer:
var cardNumber = 0;
A function to generate an id:
function newCardId() {
cardNumber ++;
return 'uniqueCardId' + cardNumber.toString();
}
And use:
var newId = newCardId();
$("#cardTable").append("<div class=\"cardLook\" id=\"" + newId + "\"></div>");
Finally to access your new div:
$('#' + newId).
Note: Escape quotes within a string using backslash!

Change background image randomly in several divs with JS

I need to change every 3000ms (with fadeIn/fadeOut effect) background image randomly in several divs
I have 4 divs, each div has background image
All images comes from one array
How can I do that?
That's my fiddle:
http://jsfiddle.net/vol4ikman/brrmkwp7/9/
var images = [
"http://placehold.it/100x100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100"
];
.images_wrapper {
width:600px;
position:relative;
margin: 0 auto;
min-height:300px;
background:silver;
padding:20px;
}
.images_wrapper > div {
width:100px;
height:100px;
overflow:hidden;
position:relative;
margin:10px;
background-color:#FFF;
border:1px solid #000;
border-radius:50%;
}
<div class="images_wrapper">
<div class="image-holder image-1"></div>
<div class="image-holder image-2"></div>
<div class="image-holder image-3"></div>
<div class="image-holder image-4"></div>
</div>
Here is basic idea as to how you can do that. I will add-in details when I get some time.
var images = [
"http://dummyimage.com/100x100/100/fff",
"http://dummyimage.com/100x100/304/fff",
"http://dummyimage.com/100x100/508/fff",
"http://dummyimage.com/100x100/70B/fff",
"http://dummyimage.com/100x100/90F/fff",
"http://dummyimage.com/100x100/AA0/fff",
"http://dummyimage.com/100x100/CB0/fff",
"http://dummyimage.com/100x100/EC0/fff"
];
//A function to shuffle the images
function shuffle(o) {
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
//Get a reference to the divs
var $divs = $(".images_wrapper > div");
//A self executing function
(function randomBackground() {
//Make an array of length = $divs.length, which is nothing but $divs.length random images form the images array;
var randomImages = shuffle(images).slice(0, $divs.length);
//Cycle thru the divs
var done;
$divs.animate({
opacity: .2
},{
start: function() {
done = 0;
},
progress: function(p, n1, n2) {
console.log(n1)
if (!done && n1 > .7) {
$divs.each(function(idx) {
//Set the background
$(this).css({
'background-image': 'url(' + randomImages[idx] + ')'
});
});
done = 1;
}
},
complete: function() {
$divs.animate({
opacity: 1
}, 400, function() {
});
}
});
//Repeat the function
setTimeout(randomBackground, 3000);
}());
Here is a demo with the complete code.
you can try this example:
var images = ['http://www.placekitten.com/250/300','http://www.placekitten.com/260/300','http://www.placekitten.com/260/310'];
var i = 0;
var allDivs = [];
function changeBackground() {
allDivs = $(".hexagon-in2").each(function(){
setBG($(this),1000);
});
}
function setBG(div, time){
var timeVar;
clearTimeout(timeVar);
if( div == undefined){
return;
}
div.css('background-image', function() {
if (i >= images.length) {
i=0;
}
return 'url(' + images[i++] + ')';
});
timeVar = setTimeout(setTimer, time);
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function setTimer(){
var imageIndex = getRandomInt(0,allDivs.length);
setBG($(allDivs[imageIndex]),3000);
}
$(function(){
changeBackground();
});
DEMO
First of all, you should use setInterval function to obtain a time loop. Afterwards you should select an image from the array on its every iteration. It can be done by calling an element from images array with a random key. To get a random number you should use: Math.random() method. Keep in mind, that it returns a float number, not integer, so you should also do the transformation.
Here is updated fiddle.
var images = [
"http://placehold.it/100x100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100",
"http://lorempixel/100/100"
];
var setInerval = setInterval(function() {
$.each($(".image-holder"), function(key, element) {
$(element).css(
'background',
'url(' + images[Math.random(0, iamges.length)] + ')'
);
});
}, 3000);
function getRandomInt(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Here is the edited code that works: http://jsfiddle.net/brrmkwp7/17/
var images = [
"https://www.video2brain.com/en/images_dynam/product_class_external_product/jquery.png",
"http://apigee.com/docs/sites/docs/files/icon_policy_javaScript.jpg"
];
var divs = ["image-1", "image-2", "image-3", "image-4"];
function setImages() {
var image;
for (var index = 0; index < divs.length; index++) {
image = 'url(' + images[Math.floor(Math.random()*images.length)] + ')';
$("#" + divs[index]).css("background-image", image);
}
}
setImages();
var setInerval = setInterval(setImages, 3000);
Basically what you need to do is to get a random number between zero and array length and use that index to select image from array, then set that to div using jquery css() function. Use each() to iterate between the divs. Make it a function and call it repeatedly using setInterval() function.
var images = [
"http://dummyimage.com/100x100/100/fff",
"http://dummyimage.com/100x100/304/fff",
"http://dummyimage.com/100x100/508/fff",
"http://dummyimage.com/100x100/70B/fff",
"http://dummyimage.com/100x100/90F/fff",
"http://dummyimage.com/100x100/AA0/fff",
"http://dummyimage.com/100x100/CB0/fff",
"http://dummyimage.com/100x100/EC0/fff"];
min = 0;
max = images.length - 1;
$(document).ready(function () {
randomImages();
setInterval(randomImages, 3000);
});
randomImages = function () {
$('.image-holder').each(function () {
var number = getRandomArbitrary(min, max);
$(this).css('background-image', 'url(' + images[number] + ')')
})
}
getRandomArbitrary = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
.images_wrapper {
width:600px;
position:relative;
margin: 0 auto;
min-height:300px;
background:silver;
padding:20px;
}
.images_wrapper > div {
width:100px;
height:100px;
overflow:hidden;
position:relative;
margin:10px;
background-color:#FFF;
border:1px solid #000;
border-radius:50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="images_wrapper">
<div class="image-holder image-1"></div>
<div class="image-holder image-2"></div>
<div class="image-holder image-3"></div>
<div class="image-holder image-4"></div>
</div>

Javascript positioning element

I try to create input controls dynamically , works fine apart from the positioning, for some reason I cant put the elements under the previous one, because I'm unable to get "style.top" property.
What I'm doing wrong and how can I fix it?
the HTML code:
<div id='div_attach' class='scrollbox' style='top: 380px; height: 65px; left: 100px; right: 135px;'>
<a href='goes_nowhere' style='top: 5px; left: 5px;'>click_me_if_you_dare</a>
</div>
<button type='button' style='top: 380px; width: 120px; right: 10px; height: 20px;' onclick='createFileInput("div_attach");'>new input</button>
the JS code:
function createFileInput(parentID) {
var atop, index;
var parent = document.getElementById(parentID);
var control = document.createElement('input');
control.setAttribute('type', 'file');
elements = parent.getElementsByTagName('*');
// debug only ...
for (index = 0; index < elements.length; ++index) {
alert(elements[index].style.top);
alert(elements[index].style.height);
};
if (elements.length > 0)
atop = elements[elements.length - 1].style.top + elements[elements.length - 1].style.height + 5;
else
atop = 5;
control.setAttribute('name', 'FILE_' + elements.length);
control.className = 'flat';
control.style.left = 5 + 'px';
control.style.top = atop + 5 + 'px';
// control.style.top = (elements.length * 30) + 5 + 'px';
control.style.width = 500 + 'px';
parent.appendChild(control);
control.focus();
}
The code:
atop = elements[elements.length - 1].style.top + elements[elements.length - 1].style.height + 5;
will return something like "5px5" because it's a string to which you append 5.
Replace it with
atop = parseInt(elements[elements.length - 1].style.top, 10) + parseInt(elements[elements.length - 1].style.height, 10) + 5;
Make sure those element have a top and height value, or else parseInt() will return NaN.
edit: In the example, the <a> has no height.

Categories