Is it possible to animate captions and slides individually within a Bootstrap 5 carousel?

Beginner coder here, testing my skills with a self-assigned task.

I've created a carousel using Bootstrap 5 with three slides, each containing two lines of captions. As the slides transition, the captions move in opposite directions—up and down. However, I'm facing a problem: because the caption div is nested within the slide div, the animations cause the captions to move diagonally during the transition, and there's also a gap between the slides.

I've almost fixed it but I'm struggling with separating the caption div from the slide div without causing overlapping issues when new captions appear. Is there a way to prevent interference between the two divs?

You can see the issue in this Codepen: https://codepen.io/AlexanderSplat/pen/YzZvEaM

And here's the same Codepen with the caption divs taken out for reference: https://codepen.io/AlexanderSplat/pen/vYxROqo

I've also included the code snippets below, but they may not work due to a recent Fastly disruption:

Incorrect transitions:

...

Good transitions, but with text overlap:

...

Answer №1

I've made several adjustments to your (second) code.

HTML

  • I have removed all unnecessary imports (animated.css, jquery, font-awesome).
  • Added the class hidden to the h1 with classes caption-top and caption-bottom that do not correspond to the first slide.

CSS

  • Replaced .carousel-caption with .carousel-top, while adding another .carousel-caption for setting the default top property.
  • Changed .slide to .hidden for better clarity.
  • Previous values have been commented for reference.

JS

Now for the fun part! Here are the changes and explanations:

  • Replaced slideclass with hiddenClass.
  • Changed all selected .caption-top to topcap and all .carousel-caption to captions.
  • Added functionality to the variables currentItem and nextItem to store the current and next .carousel-caption element for each slide.
  • Set the first .carousel-caption element (position zero) corresponding to the first slide on DOMContentLoaded to currentItem.
  • Used the relatedTarget property in both event types slide.bs.carousel and slid.bs.carousel. According to Bootstrap's documentation:

relatedTarget: The DOM element being slid into place as the active item.

nextElementSibling refers to the element immediately following. Based on the HTML structure, we can infer that a .caption-item is followed by a .carousel-caption. The usage of firstElementChild and lastElementChild is self-explanatory :)

  • At slid.bs.carousel, nextItem is displayed, while at slide.bs.carousel, currentItem is hidden (during the transition to the next slide).

...
...
...

Answer №2

const topcap = document.querySelectorAll(".carousel-caption");
const bottomcap = document.querySelectorAll(".caption-bottom");
const slideclass = ("slide");

var TACarousel = document.querySelector("#CarouselTextAnim");

TACarousel.addEventListener("slide.bs.carousel", function() {
  topcap.forEach(cap => cap.classList.add(slideclass));
  bottomcap.forEach(cap => cap.classList.add(slideclass));
});

TACarousel.addEventListener("slid.bs.carousel", function() {
  topcap.forEach(cap => cap.classList.remove(slideclass));
  bottomcap.forEach(cap => cap.classList.remove(slideclass));
});
.carousel-inner .carousel-item {
  transition: transform 1s ease;
}

.h1-carousel {
  width: 100%;
  text-align: center;
  color: white;
  text-shadow: 1px 1px 2px rgba(2, 15, 19, 0.70);
  font-family: 'Julius Sans One';
  font-style: normal;
  font-weight: 400;
  font-size: 4vw;
  transition: 0.4s;
}

.carousel-caption {
  position: absolute;
  top: 40%;
  opacity: 1;
  transition: 1s;
}

.carousel-caption.slide {
  top: 0;
  opacity: 1;
}

.caption-bottom {
  position: relative;
  bottom: 4vh;
  opacity: 1;
  transition: 1s;
}

.caption-bottom.slide {
  bottom: -90vh;
  opacity: 1;
}
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width initial-scale=1.0">
  <title>Top Motion Productions</title>
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22404d4d56515650435262170c120c120f4047564310">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.2/css/all.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.2/css/v4-shims.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,300italic,400,700|Julius+Sans+One|Roboto+Condensed:300,400" rel="stylesheet" type="text/css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://kit.fontawesome.com/a076d05399.js"></script>
</head>

<body>
  <div class="container-fluid" style="padding: 0" id="carousel">
    <section class="slideshow">
      <div id="CarouselTextAnim" class="carousel slide carousel-slide" data-bs-ride="carousel" data-bs-interval="2000" data-bs-pause="false">
        <div class="carousel-inner">
          <div class="carousel-item active">
            <img src="https://cutewallpaper.org/21/black-1920x1080-wallpaper/Dark-Desktop-Backgrounds-1920x1080-,-Best-Background-Images-.jpg" class="img-carousel d-block w-100" alt="">
            <div class="carousel-caption">
              <h1 id="carousel1" class="h1-carousel mb-5 caption-top">TOP CAPTION</h1>
              <h1 class="h1-carousel mb-5 caption-bottom">BOTTOM CAPTION</h1>
            </div>
          </div>

          <div class="carousel-item">
            <img src="https://wallpapercave.com/wp/THsknvO.jpg" class="img-carousel d-block w-100" alt="">
            <div class="carousel-caption">
              <h1 class="h1-carousel edit1 mb-5 caption-top">UP TOP</h1>
              <h1 class="h1-carousel mb-5 caption-bottom">DOWN LOW</h1>
            </div>
          </div>
          <div class="carousel-item">
            <img src="https://wallpapercave.com/wp/z7tXPkz.jpg" class="img-carousel d-block w-100" alt="">
            <div class="carousel-caption">
              <h1 class="h1-carousel edit1 mb-5 caption-top">OVER</h1>
              <h1 class="h1-carousel mb-5 caption-bottom">UNDER</h1>
            </div>
          </div>
        </div>
        <button class="carousel-control-prev" type="button" data-bs-target="#CarouselTextAnim" data-bs-slide="prev">
        <span class="carousel-control carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
      </button>
        <button class="carousel-control-next" type="button" data-bs-target="#CarouselTextAnim" data-bs-slide="next">
        <span class="carousel-control carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
      </button>
      </div>
    </section>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f99a968b9cb9cbd7cfd7c9">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c6cbcbd0d7d0d6c5d4e4918a948a9489c6c1d0c596">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.js"></script>
</body>

Just modify the transition speed from 2s to 1s. Please review the snippet

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 are some ways to utilize the pseudo elements ::before and ::after within the Material-UI framework?

Can someone please explain how to use the pseudo-element method in MUI? I couldn't find clear instructions in the documentation, so I decided to post a question here. The docs mention the following about pseudo elements: The box-sizing property is ...

A guide on showcasing a MultiPolygon GeoJSON on a Leaflet map

I am attempting to showcase a GeoJSON MultiPolygon object on a Leaflet map. I retrieve it from a PostgreSQL database as JSON and transform it into GeoJSON. I have validated the MultiPolygon object on GeoJSONLint and it checks out: However, I am facing di ...

behind the scenes of a disappearing bootstrap modal

Greetings everyone! Currently, I am deep into the process of identifying and resolving a pesky bug that has been impacting my work. The project in question involves developing a module for an open-source platform built on Laravel and Bootstrap - Microweb ...

Ways to make video controls visible following the initial click on the video

I have a collection of videos on my website and I would like them to display with a poster (thumbnail image) initially. The video controls should only appear once the user clicks on the video for the first time. Therefore, when the page is loaded, the cont ...

Interactive section for user input

I am looking to add a commenting feature to my website that allows for dynamic editing. Essentially, I want users to be able to click on an "Edit" span next to a comment and have it transform into an editable textarea. Once the user makes their changes and ...

Deactivate zoom on the viewport and display the entire page

Hello, I am currently working on my website www.ecogo.io and I am trying to get the entire page to display instead of just a portion. However, I am encountering an issue where the page loads zoomed in on mobile browsers like Chrome for Android, whether Des ...

creating a loop to handle AJAX requests for JSON data

My JSON call successfully loads the data.root.offer[0].region data into a div with the class .region. Here is the code snippet: $.getJSON('json/data.json', function(data) { $('.region').html('<p>' + data.root.offer[0] ...

Issues with Three.js raycaster intersectObjects

I am currently working on a 3D scatter plot where spheres are used to represent the points, and I am attempting to show information from the points when they are clicked. After researching various answers on this platform, I believe I am moving in the righ ...

Passing JSON Data Between Functions within an Angular Controller

In my current setup using Node.js, Angular, Express, and HTML, I have a text area that gets filled with formatted text data for letters when certain buttons are clicked. <div class="form-group"> <label class="control-label" for="flyer descriptio ...

Utilizing Astro Project to gather content from various directories containing Markdown files

I am embarking on a project to convert Mark Down files (MD) into HTML format. While delving into this endeavor, I have chosen to utilize Astro due to its compatibility with MD to HTML conversion, even though I am relatively new to ASTRO or JSX style coding ...

Find your favorite artist on Spotify through the search function

Recently, I stumbled upon this intriguing demo showcasing how to search for an artist using the Spotify API. However, despite several attempts, I have been unable to make it function properly. Can anyone provide any tips or guidance on making this work suc ...

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...

Activate the textbox without utilizing `.focus()` method

I am encountering an issue with a small iframe on my page. The content within the iframe is larger than the window itself, requiring users to scroll around to view it in its entirety. Within this iframe, there is a button that, when clicked, triggers an an ...

Production build encountering unhandled TypeError in proxy

One day, I decided to tweak MUI's styled function a bit, so I came up with this proxy code: import * as muiSystem from '@mui/system'; type CreateMUIStyled = typeof muiSystem.styled; type MUIStyledParams = Parameters<CreateMUIStyled>; ...

Do not proceed with the form submission if the fields are left blank

I am facing a challenge with organizing two sets of data, "heat" and "cold", obtained from an external provider. The data is messy and I have trimmed down the code to focus on the main issue at hand. Both "heat" and "cold" have properties that users need t ...

Is it feasible to indent lines in a template without affecting the content alignment?

Creating a string with newlines that will be included in an email later. if (action) { description = ` Git pull request action: ${action} Git pull request for repo: ${req.body.repository.full_name} Git pull request for repo URL: ${re ...

Discrepancy in sorting order of key-value objects in JavaScript

Check out my jsFiddle demonstration illustrating the issue: Example Here is the HTML structure: <select id="drop1" data-jsdrop-data="countries"></select> <select id="drop2" data-jsdrop-data="countries2"></select>​ Below is the ...

Instructions for removing and recreating an input field along with its parent elements when the value of a Select tag is changed

I currently have a table with four fields, as illustrated below: Semester | Exam Status | GPA | Fee Status My query is regarding the behavior when changing the value in Exam_Status: I noticed that the Select tag-> does not clear automatically. Specifi ...

Tips for making Google search results include query strings in the returned links

I need help figuring out how to make Google search results show a URL containing a query string. Here's an example from the project I am currently working on: Instead of this link, Google search returns: If anyone has any suggestions for fixing this ...

Facebook has broadened the scope of permissions for canvas applications

I am in the process of developing a Facebook canvas application that requires extended permissions for managing images (creating galleries and uploading images) as well as posting to a user's news feed. I am currently facing challenges with obtaining ...