Generating Bootstrap carousel items dynamically using JavaScript

One of my recent achievements includes creating a webpage that displays a list of loaded data, some of which contain YouTube links.

I am currently facing a challenge in trying to showcase these videos in a bootstrap carousel due to the complexity of integrating it with the JavaScript I've implemented. To see the full demonstration, please visit: http://jsfiddle.net/cpoxy235/

Here is an overview of the HTML structure:

<html>
  <body>
    <h6>Youtube</h6>
    <div class="list-group container" id="ytgroup"></div>

    <h6>Articles</h6>
    <div class="list-group container" id="argroup"></div>
  </body>
</html>

And here is a snippet of the JavaScript used for fetching and displaying the YouTube videos and articles:

var data = [{
  "title": "Ligo First Light",
  ...
}];

function getArrayByName(name) {
  return data.filter(
    function(item) {
      return item[name];
    }
  )[0][name];
}

var youtube = getArrayByName('youtube');
var article = getArrayByName('articles');

// Code block for appending YouTube videos
for (var r in youtube) {
   var tag = document.createElement("div");
   var text = document.createTextNode(youtube[r].url);
   tag.appendChild(text);
   
   var element = document.getElementById("ytgroup");
   element.appendChild(tag);
}

// Code block for displaying article URLs
for (var r in article) {
   var tag = document.createElement("p");
   var text = document.createTextNode(article[r].url);
   tag.appendChild(text);
   
   var element = document.getElementById("argroup");
   element.appendChild(tag);
}

Although not included in the fiddle provided, I have prepared a sample of the carousel setup as follows:

<div class="carousel-inner">
  <div class="carousel-item active">
    <div class="media border p-3">
      <div class="media-body" align="center">
        <iframe width="320" height="240" src="https://www.youtube.com/embed/PJ_GI4jdpfE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
      </div>
...
</div>

Answer №1

To create a carousel, you can easily add classes and ensure that the first div of each carousel-item has an active class using the map() method as shown in the code snippet below.

var data = [{
  "title": "Ligo First Light",
  "date": "2012-06-23",
  ...
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<div class="container">
   <div class="row pt-3">
    <div class="col my-3">
        ...
        </div>
        <div id="carouselYoutube" class="carousel slide" data-ride="carousel">
            <div class="carousel-inner" id="ytgroup"></div>
        </div>
    </div>

    <div class="col my-3">
        ...
        </div>
        <div id="carouselArticles" class="carousel slide" data-ride="carousel">
            <div class="carousel-inner" id="argroup"></div>
        </div>
    </div>
   </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 message: Cannot establish the attribute 'next' on the string '/:id'

I encountered an error while trying to develop an API for a travel company. The error message "TypeError: Cannot create property 'next' on string '/:id'" keeps popping up, even though all the necessary functions are already created. con ...

What is the best method for extracting a specific value from this JSON data?

Trying to extract the text value from a JSON response? Wondering how to retrieve the 'text' field, specifically looking for "Киргизия, Бишкек, Чуйский проспект, 213" ?? { "response":{ "GeoObjectCollection" ...

Leverage the power of forkJoin in JavaScript by utilizing objects or sourcesObject

I'm currently facing an issue with my code snippet below: getInformations().subscribe( informations => { let subs = []; for (const information of informations) { subs.push(getOtherDetails(information.id)); } ...

Modify mesh in three.js scene

Is there a way to dynamically change a mesh in a group triggered by a button click? I am loading an external .obj file: loader.load( obj, function ( object ) { createScene( object, mod.tipo, pid, cor.replace("#","0x") ); }); and adding it to a gro ...

Guide on integrating React.js into an HTML development webpage

I can't seem to get this code to work properly. I have saved it as an .html file on my computer, but it's not displaying anything when I try to open it in Google Chrome. <DOCTYPE! html> <html> <head> <script src= ...

MapBox notifies when all map tiles have finished loading

Currently, I am utilizing the Mapbox GL JS API to manipulate a Mapbox map. Prior to sending my result (which is a canvas.toDataURL) to the server via HTTP, I must resize my map to a larger resolution and then use fitbounds to return to the original points. ...

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...

The Bootstrap 4 dropdown feature is not functioning properly in Angular's production environment

While developing my Angular application with Bootstrap 4, I encountered an issue with the dropdown functionality. In the development mode, everything works perfectly. However, in production mode, I received the following error: Uncaught Error: DROPDOWN: ...

Guide to retrieving SQL data from a UITableViewCell and utilizing it as login credentials for parsing MYSQL databases

https://i.sstatic.net/qLBuA.jpg Upon examining the image I attached, you will notice a table on the left side that loads SQLite data. This data is retrieved from a MYSQL database and consists of columns such as StoreID, StoreName, StoreAddr, StoreHost, St ...

React Native vector icons display enigmatic symbols

I recently installed react-native-vector, but I'm seeing strange symbols when using it. Can anyone provide guidance on how to properly utilize this library? Platform: Android import React from 'react'; import {View, Text, StyleSheet} from & ...

When the enter key is pressed, the form will be automatically submitted

My current implementation includes the utilization of Bootstrap input tags as shown below: myPage.html <form th:object="${field}" name="modal" method="post" th:action="@{/ajouterFieldEcran}"> ... <div class="form-group row"> <label ...

updateStatusCallback function is not defined in the Facebook example using jQuery

I've been trying to incorporate Facebook integration into my HTML code, specifically adding features like Facebook login and sharing functionalities. However, I've hit a roadblock in the process. Even after searching extensively for solutions, I ...

Searching with Jquery Ajax

For my search functionality, I am utilizing ajax jquery js. I found this useful code snippet here: However, I am facing some challenges with the following Javascript code: <script language="JavaScript" type="text/javascript"> <!-- function searc ...

"Upon exiting the Chrome tab on an iPhone, the Opentok stream's hasAudio property returns false

While switching to a different tab in Chrome on iPhone (without closing it), the publisher's stream.hasAudio value changes to false. It switches back to true only upon returning to the stream tab. Can anyone explain why this occurs and how to stop has ...

Utilizing ExtJS and its control feature

I am facing an issue with the following code block: run: function(e, row){ var me = this; var container = Ext.getCmp('centercontainer'); try { container.removeAll(); } catch(e) { } // The code snippet below is act ...

angularjs and cakephp working together to handle a request

I've implemented a method in the UsersController to add new users to the database. In the cakephp ctp views, everything seems fine as the request isn't being black-holed and I'm using 'post' for this purpose. However, when I transi ...

Modifying the DOM within a getJSON callback

My current challenge involves fetching data from the YouTube API and displaying it on my website. However, I am facing an issue where the DOM changes made inside the getJSON's callback function are not reflecting on the webpage. Even though I can see ...

Discover an Effective Approach for Transmitting Form-Data as a JSON Object

Hey there! I'm encountering a bit of an issue with sending some data as a JSON object. The problem arises when trying to send images using FormData. It seems like I need to convert my form data into a single JSON object. Can anyone assist me with this ...

What is the best way to omit a field from my query if the associated variable is empty?

I need help creating a dynamic MongoDB query function that can handle multiple field values, including cases where some fields may be empty strings. In these instances, I want MongoDB to disregard those parts of the query. Here is my current query functio ...

Why are Actions and Reducers essential components in the Redux framework?

Despite my experience with Redux, I still struggle to grasp the purpose of actions and reducers. The documentation defines a reducer as (previousState, action) => newState, a concept also seen in React's useReducer. Having one function handle all ...