Randomly swap out background images in multiple divs using JavaScript

I want to create a script that changes the background image of several divs every 3000ms with a fadeIn/fadeOut effect.

  1. I have 4 divs, each with their own background image
  2. All images are sourced from one array

How can I achieve this?

Here is the link to 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>

Answer №1

If you're looking to achieve this task, here's a simple idea to get you started. I'll provide more details when I have the 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 designed 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;
}
//Obtain a reference to the divs
var $divs = $(".images_wrapper > div");
//An immediately invoked function expression
(function randomBackground() {

    //Create an array of random images from the 'images' array that is equal to the length of $divs
    var randomImages = shuffle(images).slice(0, $divs.length);
    //Loop through each div
    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() {
            });
        }
    });
    //Call the function again after 3 seconds
    setTimeout(randomBackground, 3000);
}());

Feel free to check out this demo with the entire code provided.

Answer №2

Here's an example you can test out:

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();        
});

Check out the DEMO here

Answer №3

To start, utilize the setInterval method to create a time loop for your task. Next, you'll need to pick an image from the array during each iteration by selecting an element using a random key from the images array. Generating a random number can be achieved through the use of the Math.random() method. Remember that this method returns a float, so you will need to convert it into an integer.

For the updated code, check out this revised 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;
}

Answer №4

Check out the updated code snippet that is now functional: 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 interval = setInterval(setImages, 3000);

Answer №5

To implement this functionality, you can generate a random number within the range of zero to the length of an array. This random number will be used as an index to select an image from the array. The selected image can then be applied to a div using jQuery's css() function. By using the each() method, you can iterate through each div element and apply the random images. To continuously update the images, you can create a function for this process and utilize the setInterval() function.

var images = [
    "http://example.com/image1.jpg",
    "http://example.com/image2.jpg",
    "http://example.com/image3.jpg",
    "http://example.com/image4.jpg",
    "http://example.com/image5.jpg"];
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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered: TypeScript type error in my server-side action in Next.js

Currently seeking assistance with a server action in my Next.js application. I am encountering a type error that I can't seem to identify the root cause of. This issue arises when there are three values being passed into db.insert for orderProduct, an ...

Material UI is failing to apply its styles

I tried customizing the default theme provided by Material UI, but unfortunately, the styles are not applying. Can anyone help me with this issue? In My Header.js file, I faced an issue where the customized style was not being applied as expected. const u ...

How can I display a button (hyperlink) on a new line using CSS or jQuery?

I am looking to create a new line after the last input of my form. On this new line, I want to add a "remove-link". This is my HTML: <div class="subform dynamic-form"> <label for="id_delivery_set-0-price"> Price: </label> <inp ...

The React Query devtools are failing to display

I am currently working on a project using React Query, but for some reason, the DevTools icon is not appearing on my screen. I have checked the console for errors, but there are none. I am following a tutorial on YouTube to help me with this. Here is a sn ...

A MySQL statement for inserting data that will only execute if both specified fields do not already exist

In my students database table, I want to add new data only if the email and phone number do not already exist in the table. Here is the query I attempted: INSERT INTO students (name, phone, email, address) VALUES ('vinod','9999999999&apo ...

Menu selection popper JavaScript

Struggling to create a dropdown menu and encountering this error: "Uncaught Error: Bootstrap dropdown require Popper.js (https://popper.js.org) at bootstrap.min.js:6 at bootstrap.min.js:6 at bootstrap.min.js:6" Explored various solutions in f ...

The issue of CSS stylesheet not being updated in Firefox browser on VirtualBox Ubuntu Guest with DJango and Apache configuration

While working on a Django app within a VirtualBox VM running Ubuntu 14.04, I encountered an issue with CSS stylesheets. Despite making changes to the stylesheet, the Firefox Style Inspector still displayed the old version. I have tried various methods such ...

Issue with function execution in MVC after invoking from jstree

My jquery code is supposed to trigger the MVC function call: $(document).ready(function () { alert("ddddd"); $("#divJsTreeDemo").jstree({ "plugins": ["json_data"], "json_data": { "ajax": { "type": "POST", "url": "/W ...

No data found on Angular TypeScript page with an empty array

Incorporated a function called 'getQuestionsWithInterviewId' to populate my 'Questions' string, but it appears empty when I attempt to call it within the ngOnInit and ngAfterContentInit methods and log the result in the console. import ...

Tips for utilizing ng-repeat with standard JSON data structures

I have a JSON structure like this: [{ Entry: [{ ID:123, Name: 'XYZ', Address: '600, PA' }, { ID:123, Name: 'ABC', Address: '700, PA' }, { ID:321, Name: 'RRR', ...

Encountering difficulties in transferring bulky files with the request module in Node.js

When working on a Node.js project, I encountered an issue with transferring files from the computer to the server. While I am able to successfully send files that are up to 2mb in size, larger files fail to upload. Here is the code snippet I am using: var ...

Using an if else statement in JavaScript to show varying content depending on the browser

My code includes a feature to detect the user's browser and display different content within <div> tags based on that information. However, my JavaScript logic seems to be malfunctioning. The web application is constructed using asp.net and vb. ...

Guide on retrieving JavaScript variables in a JSON response and showcasing their values on a web page

I need to show the data from a JSON response: item.php $ItemList = array(itemcode=>EATERY, itemname=>'Popcorn') ; $ItemDisplay = " '<div>' + document.write(this.itemname) + ' - ' + ...

Ways to position one div below another div

I need the #blue div positioned below the #green div The #blue div should have a margin-top: -10px; property <style> #red{ width: 400px; border: 1px solid red; } #green{ width: 100%; height: 100px; ...

How can the <dfn> tag be effectively utilized?

Even after studying the syntax and application of this tag on MDN, in a book, and various other sources, I am still struggling to see its practical significance. Maybe it's beneficial for search engine optimization? ...

What is the best way to use regular expressions in JavaScript to pull out a date value from a string?

I am working with a string in this format: var value = "/Date(1454187600000+0300)/". From this, I need to extract a date format like 1/30/2016. Currently, I have the following code snippet: var value = "/Date(1454187600000+0300)/"; // I need to extract f ...

AngularJS modal popup with a selectable table

Is there a way to open a modal popup containing a table in my application? I'm trying to achieve this by setting up an event in my app.js that triggers the modal when a row is clicked. Additionally, I need to update a field with the selected item&apos ...

html2canvas encountered a CORS error when trying to retrieve images from an external domain

I have been attempting to export a react component as a PDF file. Here are the steps I have followed: Converting the component into an image using html2canvas Creating a PDF document Attaching the image to the PDF The component contains images with URLs ...

Creating a glassy appearance: What's the process?

I want to achieve a similar glass effect as shown in this screenshot here: (), but despite trying to adjust the opacity, I can't seem to get it right. Here's my code: .Head { position: absolute; top:200px; margin-left: 20%; c ...

NodeJs / Express did not recognize the requested route

One of the key functionalities I am trying to implement is checking whether a user is authorized. If not, the template that should be rendered is my login view. This process involves requiring my router.js file in my main app.js. require('./server/ro ...