Experience a seamless transition as the background gently fades in and out alongside the captivating text carousel

I have a concept that involves three background images transitioning in and out every 5 seconds. Additionally, I am utilizing the native bootstrap carousel feature to slide text in synchronization with the changing background images.

Solving the Issue

  • Challenge 1: The initial background image is displayed upon page load. After 5 seconds, the second background image fades in while the carousel transitions to the next text. Following another 5-second interval, the third background image appears as the carousel moves to the subsequent text.

  • Challenge 2: When a user clicks on a carousel indicator, I aim for the background image to also change accordingly. For instance, clicking on indicator 1 should fade the background image to the first one. However, this transition should occur only if the clicked indicator does not match the current active item in both the carousel and background image.

Current Status

  • I have successfully implemented the fading effect for the background images using jQuery based on guidance from Stack Overflow. Similarly, I have set up the text carousel through the bootstrap component with a switching time of 5 seconds to align with the background image transitions. Despite these achievements, there is still a slight delay between the transitions. How can this delay be minimized?

  • Occasionally, the image flashes before fading, indicating room for improvement in achieving a smoother fading effect without any flickering. Are there better methods to address this issue?

  • The challenge lies in ensuring that clicking on a carousel indicator triggers a seamless transition of the background image to correspond with the selected carousel item. Despite attempting to implement a function for this purpose, it seems ineffective. What steps should be taken to achieve this functionality correctly?

Here are the approaches I have explored:

// JavaScript code snippet
var bgImageArray = ["1_ozdgvm.jpg", "2_vjtjfy.jpg", "3_oxpdx2.jpg"],
  base = "https://res.cloudinary.com/iolamide/image/upload/v1604569872/home_banner_",
  secs = 5;
bgImageArray.forEach(function(img) {
  new Image().src = base + img;
});

function backgroundSequence() {
  window.clearTimeout();
  var k = 0;
  for (i = 0; i < bgImageArray.length; i++) {
    setTimeout(function() {
      document.getElementById('animated-bg').style.backgroundImage = "url(" + base + bgImageArray[k] + ")";
      if ((k + 1) === bgImageArray.length) {
        setTimeout(function() {
          backgroundSequence()
        }, (secs * 1000))
      } else {
        k++;
      }
    }, (secs * 1000) * i)
  }
}

backgroundSequence();

$('.carousel-item').click(function() {
  backgroundSequence();
})
// CSS styles
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
}

html {
  box-sizing: border-box;
}

body {
  box-sizing: inherit;
  color: #fff !important;
}

.animated-bg {
  // Add your background image properties here
}

.container {
  // Adjust container styling as needed
}

.text-top p {
  // Additional style rules for text section
}

h1 {
  // Customize heading styles
}

.carousel-item p {
  // Styling for carousel items
}

@media only screen and (max-width: 800px) {
  // Responsive design considerations
}

@media only screen and (max-width: 500px) {
  // Adjustments for smaller screens
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<div class="animated-bg" id="animated-bg">
  <div class="container">
    <div class="text-top" id="texttop">
      <h1>Crossfade and Text Carousel</h1>
      <p>Fade background image and swipe text at the same time. Also fade the background image to the one that matches the carousel's text when the carousel's indicator is clicked</p>
    </div>
    <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-interval="5000">
      <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-inner">
        <div class="carousel-item active">
          <p>
            Carousel Text One
          </p>
        </div>
        <div class="carousel-item">
          <p>Carousel Text Two</p>
        </div>
        <div class="carousel-item">
          <p>Carousel Text Three</p>
        </div>
      </div>
    </div>
  </div>
</div>

Answer №1

You can simplify the process of changing images by utilizing the carousel API to listen for slide changes. This way, you can switch the image accordingly without having to manually handle all the logic yourself. Check out the documentation on('slide.bs.carousel') for more information.

const bgImageArray = ["1_ozdgvm.jpg", "2_vjtjfy.jpg", "3_oxpdx2.jpg"],
  base = "https://res.cloudinary.com/iolamide/image/upload/v1604569872/home_banner_";
  
bgImageArray.forEach(function(img) {
  new Image().src = base + img;
  // caches images, avoiding white flash between background replacements
});
  
$('.carousel'). on('slide.bs.carousel', function(e) {
  $('.animated-bg').css({
    backgroundImage: `url(${base}${bgImageArray[e.to]})`
  });
});
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
}

html {
  box-sizing: border-box;
}
...
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
...

https://jsbin.com/mewiwuv/edit?js,output

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

Reverting Vue Draggable Components to Their Original Position Upon Dropping Them

In my Vue 3 project, I'm implementing vuedraggable to enable element reordering within an expansion panel. However, I've encountered an issue where the dragged elements revert to their original positions upon release. This behavior suggests that ...

Shake up your background with a random twist

Seeking assistance with customizing the Aerial template from HTML5UP. I am interested in selecting a scrolling background randomly from a pool of images. Can someone guide me on how to achieve this? Presently, the background is defined within a code block ...

What is the best way to incorporate multiple input boxes into a single alertbox for repeated use?

I attempted to use the same alertbox for 3 different input elements by converting it into a class and using getElementsByClassName, but unfortunately, it did not work as expected. Here is what I tried: <input type="text" class="form-control date notif" ...

The XPath for pagination is incorrect

Whenever I try to navigate to the next page, I keep encountering an error from the robot. Can someone help me construct the xpath using either of these snippets: <li title="2" class="ant-pagination-item ant-pagination-item-2" tabind ...

Creating a repository of essential functions in AngularJSDiscover the steps to set up a

I am looking to create a set of reusable functions in AngularJS for CRUD operations that can be used across multiple entities in my project. I have already set up a factory using $resource for server communication, which looks like this: Model File: var ...

Is it possible to use an ngClick function in one directive to toggle data in another?

Currently, I am in the process of developing a weather application using Angular 1.5.8 where users should have the option to switch between imperial and metric units for temperature and wind speed. The toggle feature along with all the weather data fetche ...

Methods for retrieving a file within a nodejs project from another file

Currently, my project has the following structure and I am facing an issue while trying to access db.js from CategoryController.js. The code snippet I have used is as follows: var db = require('./../routes/db'); Upon attempting to start the No ...

Top method for displaying loading popup using $http

As a newcomer to Angular, I am curious to know if it's possible to achieve the following scenario and also where I can find documentation to help me get started. The scenario: In my MEAN app, there is currently a 'loading...' popup controll ...

What is the process for updating the CSS style of every other piece of data (such as an image) retrieved

Is it possible to utilize PHP code when retrieving data from a MySQL database in order to have every other record display with unique CSS formatting? For instance, I am incorporating images similar to this in my comment system: http://prntscr.com/3hpiep ...

What is the best way to transform a JSON object with various key-value pairs into a list using JavaScript?

There's a JSON string that I need to convert into a different format, here is the original: var jsonData = [{"label":"Hass1(<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="354d4d4d6a465058755d5a4158545c591b565a58">[emai ...

worldpay implements the useTemplateForm callback function

My experience with implementing worldpay on my one-page Angular app (Angular 1.x) has been mostly positive. I have been using the useTemplateForm() method to generate a credit card form and retrieve a token successfully. However, I have encountered an issu ...

Why is `screen` important?

Recent articles in June 2020 discussing "how to utilize react testing library" often showcase a setup similar to the one below: import React from 'react'; import { render, screen } from '@testing-library/react'; import App from '. ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Enhance your Kendo UI File Manager by incorporating image uploading and folder renaming capabilities

Currently utilizing the kendo UI file manager to navigate through my files and images. According to telerik documentation, only the functions to add folders and remove files and folders are supported. However, I am in need of the ability to rename both f ...

The file_get_contents() function encountered an issue as the content type was not specified, leading to it assuming

I am currently working on a project using PHP and JavaScript. I need to call an API from the camera using PHP code. I am using the file_get_contents function and Post request for this purpose. Below is the code snippet: $value = $_POST['TakeNewPic&ap ...

The reduce function is displaying an undefined result

Check out this code snippet: const filterByType = (target , ...element) => { return element.reduce((start, next) =>{ if(typeof next === target){ start.push(next) } } , []) } I'm trying to achieve a specific g ...

Flip the Script: JQuery slideshow in reverse

Hey there, I've been tinkering with a JQuery slideshow and encountering an issue. All my images in the HTML are stacked on top of each other, and I attempted to modify the code so it starts with the last image. However, my attempts have not been succe ...

Oops! Looks like there was an error. The text strings need to be displayed within a <Text> component in the BottomTabBar. This occurred at line 132 in the

My app includes a bottomTab Navigation feature, but I encountered an error: Error: Text strings must be rendered within a <Text> component. This error is located at: in BottomTabBar (at SceneView.tsx:132) in StaticContainer in StaticCont ...

Issue with toggling options in q-option-group (Vue3/Quasar) when using @update:model-value

I'm a newcomer to the world of Quasar Framework and Vue.js. I recently tried implementing the q-option-group component in my simple application but encountered an issue where the model-value and @update:model-value did not toggle between options as ex ...

How can I target an element with inline styling using CSS?

How can I target headings with inline style 'text-align: center' in my CSS so that I can add ::after styling to them? This is for a WordPress CMS, specifically to modify content in the WYSIWYG editor used by clients. Here's an example of th ...