Using an array of objects to set a background image in a Bootstrap carousel using jQuery: a step-by-step guide

I have an array of items, each containing a background property with a URL to an image. Here is my array:

Here is the HTML structure:

<div id="myCarousel" class="carousel slide" data-ride="carousel">
        <ol class="carousel-indicators"></ol>
        <div class="carousel-inner" role="listbox"></div>
        <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>
    </div>

And here is the script using a jQuery plugin:

$(items).each(function(index){
                $('.carousel-inner', self).append('<div class="item"><div class="container"><div class="carousel-caption">' + this.tournamentName + ' / ' + this.matchStatusName + '</div>');
                $('.carousel-inner div.item.active').css('background', 'url(' + this.background + ')');
                $('.carousel-indicators', self).append('<li data-target="#myCarousel" data-slide-to="'+index+'"></li>');
                $('.carousel-indicators li:first, .carousel-inner div.item:first', self).addClass('active');
                $(self).carousel();
            });

I have tried setting the background like

$('.carousel-inner .item.active').css('background', 'url(' + this.background + ')');
and
$('.carousel-inner div.item.active').css('background', 'url(' + this.background + ')');
but it only shows the first item with that image and stays that way until reaching the end of slides.

Can anyone provide some assistance?

Answer №1

The issue lies with the selection of

$('.carousel-inner div.item.active')
in your code. The problem is that you are attempting to target a div with the active class, but this class does not currently exist on your div.

To resolve this issue, update the following line of code:

$('.carousel-inner div.item.active').css('background', 'url(' + this.background + ')');

to:

$('.carousel-inner div.item:eq('+index+')').css('background', 'url(' + this.background + ')');

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

Placing an absolutely positioned element on top of other elements

Currently, I am working on a frontendmentor website and encountering difficulty in positioning the shopping cart div above all the other elements. Initially, I attempted to use z-index for this purpose, but it seems that it does not work with elements havi ...

Webstorm encounters difficulties compiling Sass

While attempting to utilize Sass in the Webstorm IDE, I noticed that it is defaulting to Ruby 1.8 (OS Default) instead of my preferred RVM Ruby Version (1.9.x). To address this issue, I tried setting the path for Sass in the Watcher-Configuration: PATH=$ ...

What is the best way to transfer data from a clicked table row to another component?

I am currently working on developing an email inbox component for a system where the emails are displayed in a table format. When a user clicks on a specific row, it should lead to another component for further details. Since the information is not rende ...

What is preventing me from utilizing a dynamic import while working with Nuxt3?

I'm currently working on developing a component that allows me to dynamically import icons based on the provided icon name using unplugin-icons. However, I'm facing an issue where dynamic imports don't seem to work when the import path is dy ...

Modifying Copyright Feature in Footer

I am attempting to implement this function within my dark-colored footer: import Typography from '@material-ui/core/Typography'; function Copyright() { return ( <Typography variant="body2" color="textSecondary" align="center"> ...

Attach the JSON data to the dropdown menu using jQuery

On my asp.net website, I have generated a JSon string using the JavaScriptSerializer class in JavaScript. Then, I displayed the Json string within the HTML markup by utilizing the RegisterStartupScript method and here is how it appears: This is the C#.net ...

Guide to utilizing a download link for file retrieval in Python

I'm currently working on creating a script that can automatically download specific files from webpages and save them to designated folders. For the most part, I've been successful in achieving this using Python, Selenium, and FirefoxPreferences ...

Can you explain the purpose of the behavior: url(); property in CSS?

While browsing the web, I came across a CSS property that caught my eye. It's called behavior, and it looks like this: #element{ behavior: url(something.htc); } I've never used or seen this property before. It seems to be related to Internet ...

Navigating directories and file locations in a Node/Express application

An example of my Node/Express app's file structure is shown below: /lib coolStuff.js /routes funRoute.js /views sickView.hbs app.js In the past, I have been using relative paths like var coolStuff = require('../lib/coolStuff'); to re ...

Having trouble getting PHP Ajax File Upload to function properly?

I am using Bootstrap and have a Form in a Modalbox. There is a Fileupload field, and I want to upload images. However, when I click the Submit button, the site seems to reload instantly and there is no file uploading... Below is my Ajax Script: <scri ...

Can Ansible and Pulumi be integrated to work together effectively?

Is it possible to create multiple DigitalOcean droplets in a loop and then use Ansible to configure software and security measures on them, similar to how Terraform works? If so, what would the JavaScript/TypeScript code for this look like? I couldn' ...

Should the .js file type be omitted in the <script> tag for semantic accuracy?

Upon reviewing some inherited code, I noticed that JavaScript files are being linked in the following format: <script src="/js/scriptfile" type="text/javascript"></script> However, I was expecting to see: <script src="/js/scriptfile.js" ...

What is the correct way to invoke a static TypeScript class function in JavaScript?

Recently, I encountered a scenario where I have a TypeScript script called test.ts structured like this: class Foo { public static bar() { console.log("test"); } } The requirement was to call this TypeScript function from plain JavaScript ...

Obtaining a fresh access token from a refresh token using the googleapis npm library

I've been searching everywhere for an explanation, but I can't seem to find one. The documentation I've read says that refresh tokens are used to obtain new access tokens, but it doesn't explain the mechanics behind it. Normally, I wou ...

Exploring the Differences in CSS Styling between Web and Mobile Platforms

Recently, I launched my new website and encountered a peculiar issue. Upon clicking on Pickup Date & Time, a bootstrap datepicker pops up like it should. However, the problem arises when viewing the website on mobile devices - the datepicker appears offsc ...

A commonly used method to adjust the width of a table column to accommodate the size of the child element

I have a specific table width of 776 pixels with three columns. The third column has a fixed width of 216 pixels, but the widths of the other two are unknown. I want the second column to adjust its width based on its content, and whatever space is left aft ...

The average duration for each API request is consistently recorded at 21 seconds

It's taking 21 seconds per request for snippet.json and images, causing my widget to load in 42 seconds consistently. That just doesn't seem right. Check out this code snippet below: <script type="text/javascript"> function fetchJSONFil ...

Issue: ENOENT - The requested file or directory cannot be found in the context of an Angular2 and Express.js

I have made some changes to the Angular2 app on GitHub in order to use Express.js instead of KOA. However, when I try to load the app in FireFox, I encounter the following error in the `nodemon` console: Error: ENOENT: no such file or directory The Angul ...

The aria-label attribute does not seem to be functioning properly in Chrome and Firefox when using NVDA screen

Within my code, I have a straightforward textbox element: <input type="text" aria-label="First Name" title="First Name" /> Upon hovering over the textbox, I am displaying the tooltip First Name. I attempted to utilize both aria-label and aria-labe ...

Displaying a message text upon successful AJAX request

I have a web page with an AJAX request that updates data in the database. After the update, I want to display a message to the user on the webpage confirming that the data has been successfully updated. However, currently, no message is being displayed and ...