Using Javascript and jQuery to create an infinite animated background change with fade effect

I am struggling to figure out how to automatically change the background of a div every 3 seconds, looping through a series of images. I posted about this issue before but didn't receive much help.


function animate() {  
    change1();
    change2();
    change3();
}
function change1() {  
       window.setInterval(function(){
        $('.content').css('background-image','url(http://crondon.guko.co.uk/wp-content/uploads/2015/11/bride_groom_baronial_hall1.jpg)');$('.content').css('transition','background 1s linear');
    },3000);
    }
    function change2() {  
       window.setInterval(function(){
        $('.content').css('background-image','url(http://crondon.guko.co.uk/wp-content/uploads/2015/11/confetti.jpg)');$('.content').css('transition','background 1s linear');
    },3000);
    }
    function change3() {  
       window.setInterval(function(){
        $('.content').css('background-image','url(x)');$('.content').css('transition','background 1s linear');
    },3000);
    }
    animate();

Answer №1

This task was made more complicated than it needed to be. Simply create an array containing the URLs and a function to handle setting the slide URL, initiating the transition, and updating the slide index. Then, use setInterval() to call this function at regular intervals.

var currentIndex = 0;
var urls = [
    'http://crondon.guko.co.uk/wp-content/uploads/2015/11/bride_groom_baronial_hall1.jpg',
    'http://crondon.guko.co.uk/wp-content/uploads/2015/11/confetti.jpg',
    'http://media.caranddriver.com/images/media/51/dissected-lotus-based-infiniti-emerg-e-sports-car-concept-top-image-photo-451994-s-original.jpg'
];
var length = urls.length - 1;

function slide() {
    $('.content').css('background-image', 'url(' + urls[currentIndex] + ')');
    $('.content').css('transition', 'background 1s linear');
    currentIndex = (currentIndex < length) ? currentIndex + 1 : 0;
}

slide();

window.setInterval(slide, 3000);
.content {
    height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content"></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

I seem to be having some issues with the functionality of .not() and it's

I am working on creating a menu that remains open for a set amount of time and then fades out if neither the parent nor the menu is hovered over. The goal is to have all other menus close when hovering over a new parent in the menu, but the current code k ...

Null Value Returned When Making an Ajax Post Request

I'm having trouble retrieving the id of the last inserted row after posting via ajax. When I var_dump the result, the function returns HTML instead of the id data. What am I missing here? Note: The save method should return the id of the last inserte ...

Having trouble with object initialization in a jQuery GET request?

Looking to create an HTML button using jQuery that, upon clicking the chart button, will retrieve values from specified text inputs. These values will then be used to construct a JSON object which will subsequently be included in a GET request. $(".chart" ...

Modifying routes within the beforeEach function causes issues when the callback incorrectly passes in erroneous routes to and from

I'm currently in the process of developing a mobile frontend using Vue. My goal is to have route transitions dynamically change to slide either left or right based on the current tab index. To accomplish this, I've set up a transition component ...

Utilizing JavaScript to retrieve data from a self-submitting form

From my database, I am able to create a list of options for users to choose from. Once a selection is made, the values are submitted back to the same page and retrieved using Javascript. Within the same form, there are radio buttons and a multiple selecti ...

Checking the response from an AJAX call with an if/else statement

Is there a way to create a counter for unread messages using PHP and jQuery? Below is the PHP code in BubbleStat.php: $totalMsg = $mysql->totalRows("SELECT msg_id from messages WHERE msg_opened = 0 AND msg_receiver = '".$_SESSION["ActiveUserSessio ...

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

Steps to Show an Image When Hovering and Clicking on the Relevant Div

CSS: .imgECheck { position: absolute; top: 0; right: 5px; width: 15px; height: 15px; display: none; } .imgFCheck { position: absolute; top: 0; right: 5px; width: 15px; height: 15px; display: none; } Is ther ...

What is the method for showing a JavaScript variable in a popup window?

I am having an issue with a search form that is supposed to display a list of persons based on filters. Once the search results are shown, I want a link (id=names_list) that, when clicked, will open a dialog box containing the names of the persons. I have ...

Creating an array by extracting items from a textarea that are separated by line breaks

I am working with a textarea that has the id #list : $text = $('#list').val(); The goal is to split this text into pieces and place each piece as a new item in an array. This array will then be sent to PHP, where I can utilize it in a foreach l ...

Use the Google Maps API to dynamically add a marker via AJAX once the map has been initialized

Although I have come across similar questions with related titles, none of the answers quite fit my needs. Here is the problem I am facing: I'm working on printing a map that contains multiple markers generated from a database. Below the map, there ...

JQuery Ajax: Issue with updating Total Likes for posts when Like button is clicked

There are two JQuery Ajax calls in this scenario. The first call retrieves user messages from MySQL, along with the number of likes for each message and a button for users to like the message. This initial request is functioning correctly. The second Ajax ...

Searching with jQuery UI Autocomplete

I am interested in implementing jQuery UI autocomplete to allow users to search for items on my website. I have a list of products that I want to convert into JSON data (or just include them directly in JavaScript like the jQuery UI demo does), but I&apos ...

Creating Awesome Icons in Kendo Grid with Code In this tutorial, we will learn how to programm

Looking to have a Kendo grid display a green fas-fa-clock icon if isActive is true, and a grey far-fa-clock icon if false. Clicking on the icon should toggle between true and false. Currently, the grid just shows the word true or false in the column. Cod ...

In search of a React.js/Redux OpenID library or example, particularly focused on Steam OpenID integration

Currently, I am developing a Node/Express REST + React/Redux application that requires Steam OpenID for authentication. Despite searching extensively for tutorials, libraries, or example code related to Steam OpenID (or any other OpenID), I have come up em ...

Using useState to initialize a long value

Obtaining a very large state from JSON can be challenging, especially when it consists of at least 50 lines. During page generation, an error like "there is no such value" may occur if the initial value is not set and the interface is not assigned properl ...

ApolloError: Undefined fragment detected and unable to be used

Within the complex structure of my application, I encounter the following: import { gql } from '@apollo/client'; gql` fragment StuffTable on Stuff { id status } `; export const GetStuffDocument = gql` query GetStuff($id: ID!) { ...

Looking for a way to assign customized thumbnails to images in react-responsive-carousel and react-image-magnifiers?

I am currently working on a product viewer using react-responsive-carousel and react-image-magnifiers. Following an example from this GitHub repository, I encountered an issue with mapping custom thumbnails correctly. Although hard-coding the array works f ...

Removing items dynamically from a list created using ng-repeat

I have an array of nested JSON objects and I am using ng-repeat to create a list with the nested arrays. My goal is to dynamically delete items from this list upon button click by calling a function in the controller: $scope.remove= function(path){ va ...

Determining the scrollWidth of a div with an absolutely positioned child div

Having some trouble determining the width of a div's content instead of the div itself. The typical solution would involve using Javascript's scrollWidth property. However, there is a complication in this case. Inside the div, another div is ab ...