Using a Javascript array within a Bootstrap carousel allows for dynamic content to

I am looking to incorporate my javascript array into a bootstrap carousel so that the carousel can display all the elements from the array and determine which picture should be shown based on the data. I also want it to display the title, subtitle, and alt text of each picture on the carousel items. However, I am unsure of how to connect the two, any suggestions? Here is an example of the array I am working with:

const data = [
    {
      src: 'italian.jpg',
      title: 'Italian cuisine',
      subtitle: 'Great italian cuisine',
      alt: 'Image of italian cuisine'
    },
    {
      src: 'mexican.jpg',
      title: 'Mexican cuisine',
      subtitle: 'Amazing mexican cuisine',
      alt: 'Image of mexican cuisine'
    },
    {
      src: 'japanese.jpg',
      title: 'Japanese cuisine',
      subtitle: 'Traditional japanese cuisine',
      alt: 'Image of japanese cuisine'
    }
  ];
document.getElementById("carousel-item").innerHTML = data;

The carousel I am using is a basic bootstrap carousel.

    <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
      <ol class="carousel-indicators">
        <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
        <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
        <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
      </ol>
      <div class="carousel-item">
        <img src="..." alt="...">
        <div class="carousel-caption d-none d-md-block">
          <h5>...</h5>
          <p>...</p>
        </div>
      </div>
        <div class="carousel-item">
          <img src="..." alt="...">
          <div class="carousel-caption d-none d-md-block">
            <h5>...</h5>
            <p>...</p>
          </div>
        </div>
        <div class="carousel-item">
          <img src="..." alt="...">
          <div class="carousel-caption d-none d-md-block">
            <h5>...</h5>
            <p>...</p>
          </div>
        </div>
      <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>
      </a>
      <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
      </a>

Answer №1

Creating a carousel using JavaScript involves several steps. First, you need to create or get an array of data. Then, loop through this array in JavaScript to create the slide and indicator elements dynamically. After creating the necessary HTML elements in the loop, you can write them to the page. It's important to ensure that these elements are structured within the carousel container.

Avoid using

document.getElementById("carousel-item").innerHTML = data;
as it does not directly insert an array into an HTML element. Instead, focus on looping through your array to generate slides and indicators accordingly.

Begin by setting up the basic structure of the carousel. Include a div where the slides will be inserted. Remove the data-ride="carousel" attribute as carousel activation should occur after the array generation, not during page load.

<div id="carouselExampleIndicators" class="carousel slide">
  <ol class="carousel-indicators" id='carousel-indicators'>
      <!-- Indicators will be added here -->
  </ol>
  <div class='carousel-inner' id='carousel-items'>
     <!-- Slides will be added here -->
  </div>
  
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>

After establishing the carousel structure, prepare the data when the page loads:

window.onload = (event) => {
   var slides=[], indicators=[], html='', activeClass
   data.forEach(item => {
     // Set up the slide
     activeClass = slides.length == 0 ? ' active ' : '';
     html = '<div class="carousel-item ' + activeClass + '">'
     html += '<img src="' + item.src + '" alt="' + item.alt + '">'
     html += '<div class="carousel-caption d-none d-md-block">'
     html += '<h5>' + item.title + '</h5>'
     html += '<p>' + item.subtitle + '</p>'
     html += '</div></div>'
     slides.push(html);
    
     // Set up the indicator
     activeClass = indicators.length == 0 ? ' class="active" ' : '';
     html = '<li data-target="#carouselExampleIndicators" data-slide-to="' + indicators.length + '" ' + activeClass + '></li>';
     indicators.push(html);
   })

   // Insert the slides and indicators into the carousel
   document.getElementById('carousel-indicators').innerHTML = indicators.join('');
   document.getElementById('carousel-slides').innerHTML = slides.join('');
   $('#carouselExampleIndicators').carousel(); 
};

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

The Material-ui DatePicker seems to be malfunctioning and as a result, the entire form is not

Struggling to get my DateTimePicker component (could be DatePicker) working after following installation instructions from various sources. I've spent a day and a half attempting to make it functional without success. If you can help me create a separ ...

update angular component after deleting an item

After deleting a contact in the table, I'm trying to refresh my contact list page but it's not working. Any suggestions? This is the list of contacts in the contact.component.ts file Swal.fire({ title: 'Do you want to delete this contac ...

What is the best way to display multiple modals in a React app?

I am facing a challenge where I need to render multiple modals based on the number of items in the 'audios' property of an object. Currently, I am using the mui modal library for this functionality. Here are the variables being utilized: const ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

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 ...

Steps for modifying a cell within a table using a button click

Hello, I am currently working on a project where I want to display a specific div portion when a user clicks on an image icon within a table. However, I am encountering an issue with the JavaScript code as it only shows the div portion in the first row and ...

Issues with passing parameters in JavaScript

I am facing an issue while passing multiple variables from a PHP page to a JavaScript function. Only the first parameter seems to be passed successfully. In the PHP code, the script is being called like this: <? $sdate = 0; $edate = 2; ?> <scrip ...

JavaScript Regular Expression for separating a collection of email addresses into individual parts

I am very close to getting this to work, but not quite there yet. In my JavaScript code, I have a string with a list of email addresses, each formatted differently: var emailList = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

What is the best way to retrieve the checkbox value using AJAX/jQuery with a Spring form?

My form contains a group of checkboxes identified by the path deliveryStatus, like so: <form:checkbox path="deliveryStatus" value="notDelivered"/> <form:checkbox path="deliveryStatus" value="delivered"/> I came across two helpful examples: E ...

What is the best way to ensure that my text always aligns perfectly to the end of the line?

I've been struggling to create a column layout where the text perfectly aligns with the end of the line, but so far, I haven't had any success. Despite my efforts to find a solution online, I have come up empty-handed. What I'm aiming for i ...

Progress bar for uploading files

Similar Question: Upload Progress Bar in PHP Looking for suggestions on a simple and effective method to implement a file upload progress bar. Interested in a solution that involves both javascript and php. Any recommendations? ...

ReactJs: How useEffect is invoked before onClick function in NextJS

I am facing an issue with a button in my Next project. Here is the code for the button: <Button minWidth={'140px'} onClick={() => exec(scope)} >Save</Button> When this button is clicked, it triggers the following function: c ...

I have been working on creating a hangman game, and although I have figured out the logic behind it, I am experiencing an issue where it is not functioning properly. After inspect

I am currently working on a basic hangman game using only HTML and JavaScript. I have the logic in place, but it doesn't seem to be functioning correctly. When I inspected the element, it showed an error saying 'undefined toUppercase.' As a ...

Console command to change paragraph tag color---Modifying the color

I am attempting to change the color of all paragraph tags on a webpage to white by utilizing the console. My initial attempt was: document.p.style.color = 'white'; However, this method did not have the desired effect. Interestingly, I have had s ...

Integrate these scripts for seamless functionality: JavaScript/AJAX and PHP

Currently, I am in the process of learning all the languages involved here and facing a challenge while trying to merge two scripts to perform a single task. The goal is to select a branch from a form option list, transmit that value from the option to a ...

Unable to showcase the worth

My code in the render method is aimed at accessing the value of arr[1].Title, however, it seems to be causing an error. public render(){ var arr; return ( { Array.apply(null, {length:this.state.length}).map((value, i) => {i*=6; return ...

Trouble with Bootstrap popover functionality

Twitter bootstrap-2.3.2 popover is being utilized in my BackboneJs project. When I click, a function is triggered to open the popover: <li> <a class="candidPopover" href="#" id="loginUser" rel="popover"><%= candidateName %></a> & ...

Incorporate a dynamic PowerPoint presentation directly onto my website

In my situation, on the client side, users can select image files (jpg|png|gif), PDF files, and PPT files which are then stored in a database. When viewing these selected files in the admin panel, I am using conditional statements to display them appropr ...

The issue with Extjs store.proxy.extraParams being undefined appears to only occur in Internet Explorer

I currently have an ExtJs store set up with specific configurations. var fieldsStore = new Ext.create('Ext.data.Store', { model : 'FieldsModel', proxy : { type : 'ajax', url : 'queryBuilder_getQueryDetails', ...

Webpack attempting to load build.js from a nested folder

I am in the process of setting up a Vue app with Vuetify and Vue Router. Everything works fine when I load the base URL "/", and I can easily navigate to /manage/products. However, if I try to directly access /manage/products by typing it into the address ...