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>
Related
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>
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;
}
I hope you understand my problem.
At the moment I have a JS-function that choses randomly a div of a specific Html-Class.
Now i would like to rewrite the function that it picks one div after the other, just like they are ordered in the HTML-content.
How can I do this?
For information: the random selection is made with jquery and looks like this:
function pickrandom() {
var elems = $(".classname");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
console.log(keep);
$(elems[keep]).click();
}
}
Thanks
$(document).on('click', '.classname', function(){
var self = $(this);
var total_items = $('.classname').length; // 10
var index = self.index(); //2 for 3rd element
if (index < total_items) {
setTimeout(function () {
$('.classname').eq(index+1).trigger('click');
}, 3000);
}
});
this will call the next clicks in 3 sec interval
i don't know why you are using a randomizer function.you can allow the user to make that click
Hopefully this helps you - can't see your markup, but it should get you on the right track. I've also changed your .click() to a .trigger('click') which should be quite a bit more dependable.
JavaScript
function pickrandom() {
var elems = $(".classname");
if (elems.length) {
var curTarget = Math.floor(Math.random() * elems.length);
console.log(curTarget);
$(elems[curTarget]).trigger('click');
// Find index of our next target - if we've reached
// the end, go back to beginning
var nextTarget = curTarget + 1;
if( nextTarget > elems.length ) {
nextTarget = 0;
}
// Wait 3 seconds and click the next div
setTimeout( function() { $(elems[nextTarget]).trigger('click'); }, 3000 );
}
}
$("div").click(function() {
var el = $(this);
setTimeout(function() {
console.log(el.text());
el.toggleClass("click");
}, 2000);
});
var random = Math.floor((Math.random() * $("div").length) + 1);
var index = random - 1;
console.log("Random number: ", random);
var clicker = setInterval(function() {
if (index === $("div").length) {
clearInterval(clicker);
console.log("cleared interval");
} else {
$("div").eq(index).click();
index++;
}
}, 2000)
div {
height: 50px;
width: 100%;
border: 2px solid black;
background-color: lightgreen;
margin-bottom: 10px;
text-align: center;
font-size: 30px;
}
.click {
background-color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Div 1
</div>
<div>
Div 2
</div>
<div>
Div 3
</div>
<div>
Div 4
</div>
<div>
Div 5
</div>
<div>
Div 6
</div>
I need to simulate a band that moves from left to right continuously, carrying 15 divs on it and moving them in a circle, like a carousel. When they reach the right margin to appear from the left.
I have the code that works for 1 div(more or less), but Im having troubles making the loop that includes all 15 divs.
What am I missing?
Here's what I have so far:
HTML
<body>
<div id="fooObject0">1</div>
<div id="fooObject1">2</div>
....
<div id="fooObject13">14</div>
<div id="fooObject14">15</div>
</body>
CSS
body {
font:76% normal verdana,arial,tahoma;
width:600px;
height:600px;
position:relative;
margin:0 auto;
border:1px solid;
}
div {
position:absolute;
left:0px;
top:8em;
width:55px;
height:70px;
line-height:3em;
background:#99ccff;
border:1px solid #003366;
white-space:nowrap;
padding:0.5em;
}
javascript
var foo = null; // object
function doMove(id) {
foo = document.getElementById(id);
foo.style.left = parseInt(foo.style.left)+1+'px';
setTimeout(doMove(id),20); // call doMove in 20msec
if(foo.style.left == "600px") {
foo.style.left = 0;
}
}
function init() {
for(i=0;i<15;i++){
var foo = document.getElementById('fooObject' + i); // get the "foo" object
foo.style.left = -i*55+'px'; // set its initial position to 0px
doMove('fooObject' + i); // start animating
console.log('fooObject' + i);
}
}
window.onload = init;
Thank you in advance!
It call an invalid function setTimeout(doMove(id), 20);.
doMove(id) return undefined, or you use "shared var" (Orientad Object) or doMove need return other function.
Note: var foo = null; // object this variable causes conflict when using setTimeout or setInterval
Try this (read my comments in code):
function doMove(id) {
return function() {
var foo = document.getElementById(id);//Global variable causes conflict when using `setTimeout` or `setInterval`
foo.style.left = parseInt(foo.style.left)+1+'px';
setTimeout(doMove(id),20); //setTimeout need an valid function
if(foo.style.left == "600px") {
foo.style.left = 0;
}
}
}
function init() {
for(i=0;i<15;i++){
var foo = document.getElementById('fooObject' + i);
foo.style.left = -i*55+'px';
doMove('fooObject' + i)(); //doMove need "()", because not run "direct"
console.log('fooObject' + i);
}
}
I modified the code for effect "carousel" and fix the problem with "left" (In 1 to 5 div):
function carrousel() {
var numberOfItems = 15; //Change this if needed
var delay = 1; //Change delay time if needed
var limitArea = 599; //Size limit your carousel area (600px, used 599 for limit with `>`)
var sizeObject = 58; //Width size of objects
//Don't change
var index = 0; //Current index
var allItems = []; //Indexed objects
//Get and index all objects
for(index = 0; index < numberOfItems; index++){//user var
allItems[index] = document.getElementById("fooObject" + index);
}
//Convert position left for int and detect "NaN"
var getPosition = function(pos) {
pos = parseInt(pos);
if (isNaN(pos)) {
return parseInt(-(index * sizeObject));
} else {
return parseInt(pos + 1);
}
};
var doMoveAll = function() {
var foo, post;
for(index = 0; index < numberOfItems; index++){//user var
foo = allItems[index];//Current object
pos = getPosition(foo.style.left);//Get position
//Detect if object are in out area
if(pos > limitArea) {
var beforeItem;
//Get before object for effect carousel
switch(index + 1) {
case 1:
beforeItem = "fooObject" + (numberOfItems - 1);
break;
default:
beforeItem = "fooObject" + (index - 1);
}
//Get position again, but used before object
pos = (
getPosition(document.getElementById(beforeItem).style.left) - sizeObject
);
foo.style.left = pos + "px";
} else {
foo.style.left = pos + "px";
}
}
//Timeout delay
window.setTimeout(doMoveAll, delay);
};
doMoveAll();//Init
};
window.onload = carrousel;
I am trying to achieve shuffle three images in a random order
This is what i have achieved so far
shuffle jsfiddle
I wanted to shuffle them with each other randomly
$(document).ready(function () {
shuffle(1);
});
var shipsArray = new Array();
shipsArray = ["1", "2", "3"];
function shuffle(level) {
for (i = 0; i < 30; i++) {
var j = i % 3;
var favorite = shipsArray[Math.floor(Math.random() * shipsArray.length)];
if (j != favorite) {
var newposition = $("#ship" + shipsArray[favorite]).position();
var tempPosition = $("#ship" + shipsArray[j]).position();
$("#ship" + shipsArray[j]).animate({ "left": newposition.left, "top": newposition.top });
$("#ship" + shipsArray[favorite]).animate({ "left": tempPosition.left, "top": tempPosition.top });
}
}
}
Here is my final solution (sort of).
I had to resort to using setTimeout() to do the timing right.
JSFiddle
HTML (unchanged, just for completeness)
<div id="MainDiv">
<img id="ship1" src="http://cdn-img.easyicon.net/png/154/15462.png" />
<img id="ship2" src="http://cdn-img.easyicon.net/png/154/15462.png" />
<img id="ship3" src="http://cdn-img.easyicon.net/png/154/15462.png" />
</div>
CSS (also unchanged)
#MainDiv {position:absolute;}
#MainDiv img {position:absolute;}
#ship1 {top:10px; left:200px;}
#ship2 {top:210px; left:0px;}
#ship3 {top:210px; left:400px;}
JS
var ships = [] /* array of ships */
var time_anim = 500 /* anim time */
$(document).ready(function () {
ships = $("#MainDiv img"); /* find ships */
shuffle(6); /* wheeee */
});
function shuffle(level) {
/* do the animation */
var c = randInt(2, 3)
cycle(getElements(ships, c))
if (level > 1) {
setTimeout(function () {
shuffle(level - 1)
}, time_anim)
}
}
function randInt(min, max) {
/* get random integer */
return Math.floor(Math.random() * (max - min + 1) + min);
}
function cycle(items) {
/* cycle ships in array */
var pos0 = $(items[0]).position()
for (i = 1; i < items.length; i++) {
var sh = items[i];
var shp = $(sh).position();
$(items[i - 1]).animate({
"left": shp.left,
"top": shp.top
}, time_anim);
}
$(sh).animate({
"left": pos0.left,
"top": pos0.top
}, time_anim);
}
function getElements(arr, n) {
/* Get n random elements from array */
var used = []
var result = []
while (result.length < n && result.length < arr.length) {
var i = randInt(0, arr.length - 1)
if (jQuery.inArray(i, used) !== -1) {
continue;
}
used.push(i)
result.push(arr[i])
}
return result;
}
(Maybe it can be done a bit easier, but w/e - it works.