Angular and Bootstrap 5 combine to create a dynamic multi-item carousel featuring animated slide transitions and embedded YouTube videos

I'm trying to create a multi-item carousel using YouTube videos, and although I have managed to get it working with Bootstrap 5 carousel and cards, the animation when the carousel slides is not as smooth as I would like. The issue seems to be that the cards overlap during the slide transition, even after adjusting the values in transform: translateX(%). Any suggestions on how to improve this?

Here is the code for the carousel, which displays 3 cards with embedded YouTube videos and titles at the bottom:

<!--Carousel Videos-->
      <div class="col-lg-12 ms-2 mt-5">
        <div class="mx-auto my-auto justify-content-center">
          <div id="recipeCarousel" class="carousel slide" data-bs-ride="carousel">
            <div class="carousel-inner" role="listbox">
                <div class="carousel-item active">
                    
                      <iframe src="https://www.youtube.com/embed/rf8vM_X1g9U" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                      
                        <p class="fs-5 fw-bold">Experience John Deere, Expo Agroalimentaria 2021</p>
                       
                    
                </div>
                <div class="carousel-item">
                    
                      <iframe src="https://www.youtube.com/embed/3xq7z7WBOGU" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                     
                        <p class="fs-5 fw-bold">Harvest in Sight, Forage Harvester 8300i</p>
                      
                   
                </div>
                <div class="carousel-item">
                    
                      <iframe src="https://www.youtube.com/embed/9PBeqHEopLs" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                      
                        <p class="p-2 mb-2 fs-5 fw-bold">Harvest in Sight, CH570</p>
                       
                    
                </div>
              
            </div>
            
          </div>
        </div>
      </div>
      <!--Carousel Videos-->

This is the CSS where I have applied the transform: translateX()%:

#cardHeight {
  height: 80px;
}

@media only screen and (min-width: 768px) {
  iframe{
    height: 24em;
  }
  .card{
    width: 100%;
  }
}

@media (max-width: 767px) {
  .carousel-inner .carousel-item > div {
      display: none;
  }
  .carousel-inner .carousel-item > div:first-child {
      display: block;
  }
}

.carousel-inner .carousel-item.active,
.carousel-inner .carousel-item-next,
.carousel-inner .carousel-item-prev {
  display: flex;
}

/* Medium and up screens */
@media (min-width: 768px) {
  
  .carousel-inner .carousel-item-end.active,
  .carousel-inner .carousel-item-next {
    transform: translateX(33%);
  }
  
  .carousel-inner .carousel-item-start.active, 
  .carousel-inner .carousel-item-prev {
    transform: translateX(-33%);
  }
}

.carousel-inner .carousel-item-end,
.carousel-inner .carousel-item-start { 
transform: translateX(0);
}

Lastly, here is the JavaScript code for the carousel functionality:

  let items = document.querySelectorAll('.carousel .carousel-item')

  items.forEach((el) => {
    const minPerSlide = 3
    let next = el.nextElementSibling
    for (var i=1; i<minPerSlide; i++) {
        if (!next) {
            // wrap carousel by using first child
            next = items[0]
        }
        let cloneChild = next.cloneNode(true)
        el.appendChild(cloneChild.children[0])
        next = next.nextElementSibling
    }
})

Here is an image of how the carousel looks in my project: carousel-image

Answer №1

I stumbled upon a new carousel that simplifies the process of creating a YouTube video carousel. I decided to use Owl carousel for this purpose, and for integrating it into Angular, I opted for ngx-owl-carousel-o which was quite easy to use and worked seamlessly with YouTube videos. To incorporate YouTube videos, all I needed was to install the YouTube player for Angular. Below, you can find my code showcasing the final output.

Below is the HTML component for the video carousel:

<owl-carousel-o [options]="videosOptions" class="videosCarrusel">
  <ng-container *ngFor="let slide of videos">
    <ng-template carouselSlide [id]="slide.id">
        <div class="card">
          <youtube-player class="card-img-top"
              videoId= {{slide.videoId}}
              suggestedQuality="default" 
              [height]="290" 
              [width]="454" 
              [startSeconds]="0"
              [endSeconds]="">
          </youtube-player>
          <div class="card-body">
            <p class="card-text">Video Title</p>
          </div>
        </div>  
    </ng-template>
  </ng-container>
</owl-carousel-o>

And here is the TypeScript component for the video carousel:

import { Component, OnInit } from '@angular/core';

import { OwlOptions } from 'ngx-owl-carousel-o';

@Component({
  selector: 'app-videos-carousel',
  templateUrl: './videos-carousel.component.html',
  styleUrls: ['./videos-carousel.component.css']
})
export class VideosCarouselComponent implements OnInit {

  // Video data
  videos = [
    {
      id: '1',
      videoId: 'YouTube Video ID'
    },
    // More video data entries here...
  ]

  constructor() { }

  // Owl Carousel options
  videosOptions: OwlOptions = {
    items: 3,
    margin: 10,
    loop: true,
    autoplay: true,
    // Other options...
    nav: true
  }

  ngOnInit(): void {
    // Script initialization for YouTube player
    const tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    document.body.appendChild(tag);
  }
}

Everything works smoothly with no issues regarding looping, autoplay, or animations. Just remember to adjust the height and width in the <youtube-player> to ensure your content fits the video frame. Hopefully, this snippet proves helpful to others as well.

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

Issue with JQUERY where HTML select element is not visible

$(document).ready(function(){ var selArr = [ {val: 'corsair', text: 'Corsair'}, {val: 'evga', text: 'EVGA'}, {val: 'antec', text: 'Antec'} ]; $('#pSupply& ...

In Node.js, it is essential to use req.session.save() to ensure that sessions are properly saved

While developing a website with Node.js, Express, and Redis for session management, I noticed an issue where my session variable (isLoggedIn) wasn't being saved after refreshing the page. Strangely, calling req.session.save() after setting the variabl ...

Swap out a portion of HTML content with the value from an input using JavaScript

I am currently working on updating a section of the header based on user input from a text field. If a user enters their zip code, the message will dynamically change to: "GREAT NEWS! WE HAVE A LOCATION IN 12345". <h4>GREAT NEWS! WE HAVE A LOCATIO ...

Converting HTML Javascript to JAVA with the help of Selenium

Can someone help me extract the value of h1 as a string using selenium? Check out the HTML javascript snippet below- <script type="text/javascript"> $(window).load(function() { var $windowHeight = $(window).height() -12; $(" ...

difficulties with struts2 user interface elements

Can anyone explain why the s:textfield is being positioned at the bottom when inserted among other HTML elements within a form? And what steps can be taken to resolve this issue? <label><span class="required">*</span>First name</label ...

.toggleClass malfunctioning inexplicably

I've been struggling to make a div box expand when clicked and revert to its original size when clicked again. It seems like a simple task, but no matter what I try, I can't seem to get it right. I'm not sure where I'm going wrong, as t ...

Utilizing Next.js to dynamically render a modal using data from the router's query parameters

I have an interactive feed that showcases cards. These cards trigger a modal to open, providing more details related to each card. The information is passed down two levels using props and everything functions smoothly until I incorporate Next Link for mod ...

Attempting to send a variable from JavaScript to PHP while inside an "if" statement

I've been attempting to pass a variable within an if statement, but for some reason the PHP file isn't receiving the variable. Below is the code I'm working with: JS: if(data.details.payment_type =="sofo") { var orderid = data.deta ...

Attempting to retrieve the MongoDB data for the designated field (data.site.alerts.alert) and transfer it to the client side

*****My code ***** import logo from './logo.svg'; import './App.css'; import React, { Component } from 'react'; import axios from 'axios'; export default class App extends Component { state = { arraydata: ...

Guide on how to position a single anchor at the center of a div alongside other elements

I am having trouble centering an anchor on my webpage. I have tried using text-align: center;, but it always puts the link on a new line due to the required div element. Other methods like margins and spans have not worked for me either. span.right { ...

What is the best way to center a rotated element and have it aligned to the top?

* { box-sizing: border-box; } body { font-family: 'Poppins', sans-serif; margin: 0px; } .we-adopt { background-color: #8a8484; color: #ffffff; padding: 88px 0px; height: 100px; } .we-adopt-list span { display: i ...

Animating an image inside a bordered div

I'm attempting to create an animated effect where an image moves randomly within the boundaries of a div container. While I've come across solutions for animating within borders, none have specifically addressed keeping the image inside the div. ...

Integrating DHTMLX Scheduler with Node JS for seamless scheduling solutions

Having diligently followed the DTHMLX Scheduler guide, I've encountered an issue with the db.event.insert() function not working, as the associated route fails to trigger. Interestingly, data from my MongoDB displays correctly when inserted via the sh ...

Hide a div using jQuery by implementing an if statement and adding a new class

I am trying to find a solution for hiding a div generated by a plugin when disabled=true. I have been researching on SO and came across the idea of using .attr to locate disabled=true and then adding a CSS class with display: none to hide it. Unfortunately ...

Executing additional code after all tests have finished in Mocha.js

In the world of MochaJS testing, it is customary to have before and after blocks for setup and teardown operations. But what if we want to execute an extra cleanup step after all test files have been processed? This is crucial to ensure that any lingering ...

Using JavaScript to call an API in PHP and determine how to handle a response that is not equal to 200 by printing an

Greetings! I am aiming for a scenario where, upon clicking the link, the user's parameter is transferred to JavaScript. This parameter will then be used in ajax to trigger a call to my PHP file containing the API. The API, after processing the parame ...

jQuery receiving improperly formatted HTML from method call

One issue I am facing involves a jQuery Ajax method that anticipates receiving HTML as the return. The JavaScript function's URL leads to a JsonResult method within ASP.NET MVC. To construct the HTML, I am utilizing StringBuilder and checking it in Vi ...

Disable editing of all form controls within a template-based form

We are looking to implement a 'read-only' feature for certain users in our template-based form that utilizes Angular Material controls such as matInput and mat-select. My initial approach was to check user privileges and then iterate through the ...

Highlighting the selected tab with an active class

Currently in the process of learning angularJs, I am still new to it and attempting to dynamically add an active class to the recently clicked tab. Within my interface, there are four tabs: insert, view, update & delete. My goal is to apply the active ...

Is there a way to use Selenium to automate the clicking of two buttons with empty href attributes? Each button has a function name and arguments within the href

Here is the HTML code for both buttons: <td> <a href="javascript:abcMy(2310);" class="btn btn-lawa btn-primary btn-primary-lawa">View</a> </td> <td> <a href="javascript:abcMy(2330);" class="btn btn-lawa btn-primary btn ...