Utilizing JQuery to create a dynamic background image slider that cycles through images extracted from a selection of

Case Study:

  • Implementing a background-image slider with JQuery listening for window resizing.
  • Depending on the screen size, a specific array is set as the image file paths source.
  • Encountering a 6-second delay issue where the initial image does not display correctly.
  • Efforts to resolve it led to the first image displaying twice instead of cycling through the array sequentially.

View jsfiddle demo

$(function(){

var img_41 = "url('https://s33.postimg.org/e11jeeisv/lagoon-467.jpg')",
img_42 = "url('https://s33.postimg.org/68avmepof/christmas-467.jpg')",
img_43 = "url('https://s33.postimg.org/cyrcvu54f/cars-467.jpg')",
img_1 = "url('https://s33.postimg.org/vr37zgr8v/lagoon-720.jpg')",
img_2 = "url('https://s33.postimg.org/mw2doxfb3/christmas-720.jpg')",
img_3  = "url('https://s33.postimg.org/f3bpwyorj/cars-720.jpg')",
img_91 = "url('https://s33.postimg.org/qsfpkxv5r/lagoon-991.jpg')",
img_92 = "url('https://s33.postimg.org/5is3a2rpr/christmas-991.jpg')",
img_93 = "url('https://s33.postimg.org/a4o7ieidr/cars-991.jpg')",
slider1 =[img_1, img_2, img_3],
slider2 =[img_41, img_42, img_43],
slider3 =[img_91, img_92, img_93],
i =0;

var $target = $('.wrapper');
var $win=$(window);
var arr;    

$win.on('resize', function() {
    var screen= $win.width();
    if(screen < 468){
        arr = slider2;  
    }
    else if(screen > 991){
        arr = slider3;  
    }
    else{
        arr = slider1;  
    }

    $target.css({
        'background-repeat':'no-repeat',
        'background-position': 'center center',
        'display':'block'
    });
}).resize();


setInterval(function() {
    $target.animate({ opacity: 0 }, 500, function() {
        console.log(arr[i]);
        $target.css('background-image', arr[i]);
        i++;
        $target.animate({ opacity: 1 }, 500, function() {
            if(i === arr.length) i = 0;
        });
    });
   }, 6000);
});

Answer №1

Check out this fiddle. Globalize all variables and create a function to handle the changes automatically.

When the document is ready, call the function and start the loop.

/*Declare global variables here*/
function slide(){
 $target.animate({ opacity: 0 }, 500, function() {
    console.log(arr[i]);
     $target.css('background-image', arr[i]);
     i++;
     $target.animate({ opacity: 1 }, 500, function() {
       if(i === arr.length) i = 0;
     });
   });

}

$(function(){
/*Other code can go here*/
        slide();
        setInterval(function() {
      slide();
    }, 6000);

});

Visit the live example on JSFiddle

Answer №2

Upon inspection, it seems you are triggering your image function after a 6-second delay. To ensure the animation is displayed promptly, consider calling the function at least once before the 6-second mark.

For reference, please review this link.

HTML:

<div class="wrapper"></div>

CSS:

.wrapper{height:500px}

jQuery:

$(function(){

var img_41 = "url('https://s33.postimg.org/e11jeeisv/lagoon-467.jpg')",
img_42 = "url('https://s33.postimg.org/68avmepof/christmas-467.jpg')",
img_43 = "url('https://s33.postimg.org/cyrcvu54f/cars-467.jpg')",
img_1 = "url('https://s33.postimg.org/vr37zgr8v/lagoon-720.jpg')",
img_2 = "url('https://s33.postimg.org/mw2doxfb3/christmas-720.jpg)",
img_3  = "url('https://s33.postimg.org/f3bpwyorj/cars-720.jpg')",
img_91 = "url('https://s33.postimg.org/qsfpkxv5r/lagoon-991.jpg')",
img_92 = "url('https://s33.postimg.org/5is3a2rpr/christmas-991.jpg')",
img_93 = "url('https://s33.postimg.org/a4o7ieidr/cars-991.jpg')",
slider1 =[img_1, img_2, img_3],
slider2 =[img_41, img_42, img_43],
slider3 =[img_91, img_92, img_93],
i =0;

var $target = $('.wrapper');
var $win=$(window);
var arr;    

$win.on('resize', function() {

        var screen= $win.width();
        if(screen < 468){
            arr = slider2;  
        }
        else if(screen > 991){
            arr = slider3;  
        }
        else{
            arr = slider1;  
        }
        $target.css({
            'background-repeat':'no-repeat',
            'background-position': 'center center',
            'display':'block'
        });
}).resize();

rotateImages($target,arr,i)
setInterval(function() {
    rotateImages($target,arr,i)
}, 6000);
});

function rotateImages($target,arr,i) {
    $target.animate({ opacity: 0 }, 500, function() {
     $target.css('background-image', arr[i]);
     i++;
     $target.animate({ opacity: 1 }, 500, function() {
       if(i === arr.length) i = 0;
     });
   });
}

We hope this information proves useful for you :)

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

What is the trick to showing text underneath a font awesome icon?

My HTML code contains font awesome icons, and I'm looking to have text appear below each icon instead of next to it. Currently, the text is displayed midway to the right of each icon. <div class="icons"> <span class="fa-stack f ...

JavaScript post method for JSON data: no input or output values

I am currently developing a page that extracts data from an HTML table consisting of two columns and an index of a form, and then converts it into a JSON string. The intention is to pass this data into PHP for further processing, perform calculations on th ...

Is it possible for me to include additional fields in a vuetify calendar event?

Is there a method to incorporate additional fields, such as a description, in addition to the name and start/end time for an event on the v-calendar's day view? ...

What steps should I follow to utilize the Ning API in order to develop a feature similar to this?

Click here for a compilation of blog posts This page provides just a simple list of the latest blog entries. For those interested in the technical side, check out this link to the API documentation I don't have much experience with coding. Any assi ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

The <img> element is able to fill an entire div while maintaining its original aspect ratio

I am currently facing a challenge with implementing a responsive gallery slider in Bootstrap. In order to achieve responsiveness, I need to use properties like max-height. The issue arises from the fact that the images in the gallery can vary in size and ...

Transform your image using a stunning zoom-in effect

Currently, I am experimenting with a feature for my website where I want images to switch upon hover. While I have successfully achieved the image switch on hover, I am looking to create smooth transitions between the switches, with the second image being ...

What are some ways to maintain the aspect ratio of an image with two dimensions?

Issue: The image is taller than the img-box container https://i.stack.imgur.com/zDBLM.png I have identified two potential solutions, but I am not satisfied with them: Removing the img-box wrapper Applying max-height and max-width properties to the img t ...

Tips for changing the size of a div using an absolute div position

Is it possible for the #parent div to resize based on the dimensions of the #child div (if the #child div is using position:absolute;)? Similar to how the #t_parent table resizes according to the size of the #t_child table. <div id="parent" style="pos ...

The incorrect sequence of Angular/Protractor functions is causing issues within the tests

Trying to extract the values from a column in a grid and compare them before and after sorting can be tricky. I have two functions set up for this task - one to retrieve the initial column values, and another to check the order post-sorting. However, there ...

Custom filter for date field in a Datatable

Could someone assist me in filtering the list of items based on the date range values selected in the date picker field? https://i.sstatic.net/hBtji.png ...

Having a tough time navigating the Bootstrap upgrade from 2.x to 3.x - now my design is all out of whack

Upgrading my site to the newest version of Bootstrap has been quite the challenge. I'm noticing that despite the window size being the same, version 1 and version 2 of my site are displaying different @media sizes. What's going on? On the left i ...

What could be causing angular-datatable to not properly fill columns in Bootstrap 4?

I have been attempting to create a responsive table using angular-datatables (for angular 7) and bootstrap 4, but I am encountering issues with the current appearance of the table: Current HTML code: <div class="row"> <d ...

What is the best location for storing buddypress css files?

Recently, I set up buddypress on a fresh WordPress installation and am interested in developing a child theme with personalized styles. Following advice from the buddypress codex, I copied the buddypress theme from plugins > buddypress > bp-template ...

Ways to solve the issue of the mobile dropdown menu in Bootstrap

Check Out the Expected Look Here (Image link) See How it Appears on Mobile Devices The dropdown menu causes an increase in the size of the navbar on the mobile version. Below is the code snippet: <div style=" background-image: url(https://i.imgu ...

What is the most effective method for attaching a jQuery click event to every anchor tag within each row of a table?

Displayed here is a grid (basic html table) showcasing users with the option to delete a specific user by clicking on the delete link. My typical approach involves: <% foreach (var user in Model.Users) {%> <tr > <td align="right"><% ...

Associating a mouse click with elements within a repetitious function

Currently, I am importing children of element with ID #parentEle, creating a duplicate of each child and adding it to an array with a new ID - #eleCopy(i). I am facing an issue where I am trying to implement a click function on the original imported objec ...

Implement a scrolling feature to the tooltip when using "data-toggle"

I'm struggling with a piece of code that showcases a tooltip when the user hovers over the question circle icon. The tooltip's content can't exceed 1000 characters, but I need to figure out how to make the overflow scroll by adjusting the to ...

What could be causing the file resumeData.json to not load correctly on GitHub pages after deployment?

After trying out this specific tutorial for deploying my personal website template found on GitHub to GitHub pages, I encountered an issue with the loading of information from public/resumeData.json. My personal page can be accessed at: The master branch ...

Load a webpage with two dropdown menus in JavaScript/jQuery that have the same selection option pre-selected

I am facing an issue with two dropdown menus that should display the same value when the page loads. These dropdowns are used for filtering products on a WooCommerce website based on the selected vehicle. Initially, the user selects the Make, Model, and Se ...