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

Ways to transform an ISO string formatted date time into the following hour

I have a function that converts my date to RFC3339 format, but I want it to be converted to the upper time limit. Could someone please help me figure out how to convert it to the upper limit? const date = new Date(); // converting to RFC 3339 format ...

How can Vue.js implement a satisfactory method for synchronizing computed values with asynchronous data?

Imagine retrieving a list of products from the state manager in your Vue.js component, where a computed property is then used to process this list for display on the DOM. <template> <span>{{ computedProducts }}</span> </template> ...

When using React Router, redirect to a new page by pushing into the browser's history

Is it feasible to utilize <link> for the purpose of <Link to="route" target="_blank"> in order to open links in a new tab? However, can we also employ browserHistory.push to achieve the same outcome? ...

Response from Vimeo's AJAX API

I am having trouble retrieving the AJAX response from Vimeo to extract a thumbnail without using JQuery. Even though I can see the response data in JSON format when I type the response query (http://vimeo.com/api/v2/video/30408418.json) into the browser an ...

Error: Attempting to modify a constant value for property 'amount' within object '#<Object>'

After fetching data from an API, I stored an array in a state. Upon trying to update a specific field within an object inside the array using user input, I encountered the error message: 'Uncaught TypeError: Cannot assign to read only property 'a ...

Sending an array input to PHP

I am having trouble sending an array input to PHP via JavaScript. The posted array does not seem to be showing up in the controller when I try to print it. Here is the relevant code snippet: submitHandler: function(form) { $('input[name="val_prof ...

Engage the PROTRACTOR refresh function

I'm just getting started with automation and Protractor. I successfully automated the login page, but now I'm facing a challenge with accessing a menu that I need in order to navigate to a different page. Within the menu, there is an href="#/dom ...

Guide to generating customized CSS styles on-the-fly in Vue (similar to Angular's dynamic styling capabilities)

When working with Angular, we have the capability to dynamically set CSS properties. For example: <style ng-if="color"> .theme-color { color: {{color}}; } .theme-background-color { background-color: {{color}}; } .theme-border-color { border-color: { ...

CSS Tutorial: Creating a Dynamic Gradient Bar

I am looking to create a dynamic colored bar with a moving color gradient effect. Without using JavaScript, I want to achieve this effect using CSS 3 properties such as gradients and animations. This is a snippet of what I have tried so far: HTML: <b ...

Using namespaces in Rails to encapsulate CSS styles

Is there a way to add namespaces to CSS within a Rails project? I have two pre-defined CSS files and two application layouts. I want the first layout to use one CSS file, and the second layout to use the other. However, both CSS files have styles for the ...

What is the process for generating Json using information from a form?

Recently, I embarked on a project that involves creating online tours via a form filled out by the administrator. The data submitted through the form is then mapped into a Mongoose Schema and transformed into JSON. In the createcontent.js file, I utilized ...

Achieving the validation with a bold red border

Hi, I'm currently learning React and I've been using regular JavaScript to validate my form. Here's a snippet of how I'm doing it: <TextField label="Title" variant="outlined" si ...

The frequency of database updates exceeds expectations - involving vue.js this.$router.push and express operations

Having some trouble updating a MongoDB with this code. It seems to be updating three times instead of just once due to having three dates in the posts.date field. Utilizing Vue, Mongo, and Express for this project, I have the following data structure: { ...

Ways to clear the time attribute from an ISO DateTime in date format

How can I remove the time attribute from a date in the format 2016-05-24T05:07:57.756Z and set it to something like 2016-05-25T00:00:00.000Z? Any assistance would be greatly appreciated. ...

CSS will only be visible if it is enclosed within the <style> tag

While creating a view, I noticed that my CSS is not being displayed unless it's placed inside a <style> tag. I've tried using !important without success, as well as utilizing the selector .container-fluid > .row > .d-flex > .out_pr ...

How can I adjust the size of my elements to be responsive in pixels

While browsing through Quora and Facebook feeds, I noticed the fixed size of user display pictures: width: 40px; height: 40px; Even when resizing the browser window for a responsive design, these pictures maintain their size at 40px x 40px. What other f ...

What steps do I need to take in order to change an HTML div's background to a black

My current project involves dynamically loading HTML content stored on disk into a specific div element. This is achieved by using the following code: $('#FictionContent').load('Content/HuckFinn.html'); Just to provide some background ...

Merge a dropdown menu with an alphabetically arranged list that is interactive with clickable options

I am still learning HTML and Javascript but I'm doing my best. Currently, I am facing a challenge where I need to create a button that, when clicked, opens a dropdown menu containing a table of data. The user should then be able to select a number fr ...

Is there a way to center the text vertically within an anchor tag?

How do I align text vertically within an anchor tag? Here's a visual representation of the issue: The text "Publisher Search," "Add a New Publisher," and "Edit a Publisher" should be aligned vertically in the "bar." This is the coding structure: & ...

What could be causing my AngularJs routing and animation to bypass the second redirection?

Recently started working with Angular and experimenting with routing and animations to manage my page transitions. I followed a helpful guide that helped me set everything up. I encountered a few issues: When trying to link back to the landing page (home ...