Delay in displaying image on bootstrap slider

I'm a beginner in JavaScript and currently learning the ropes. I have a bootstrap slider with images on each slide. My goal is to make the images appear with a slight delay on the slide where they belong. I've managed to achieve this for the first slide using the code below. However, applying my class to other images causes them to appear when the document loads rather than on the specific slide.

This is the JavaScript code I have so far:

$(document).ready(function() { 
  $('.foo').hide().delay(1).fadeIn(2200); 
});

Currently, all images fade in after the delay. How can I modify the code to only apply the fadeIn effect when the user navigates to the respective slide?

I hope I've explained my issue clearly. Please feel free to provide guidance and suggestions. Thank you.

Answer №1

If you've been using the default bootstrap carousel, I've taken a quick and simple approach to help you understand my process.

First, I locate the two buttons responsible for changing the image and store them in an array. I then loop through them and attach the fadeIn function to their click event, meaning the function will be triggered on click.

Next, the fadeIn function is defined. It iterates through all the images and adds the 'fade-in' class, which handles the styling and animation. It also adds an event handler 'transitionend' to remove the class once the animation is complete, preparing for the next trigger.

We can expand on this further by ensuring the class is added only to the image transitioning in. We can also introduce a delay using the 'animation-delay' property in CSS. However, this basic example should guide you in the right direction.

Resources Used:

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick

Using CSS for fade-in effect on page load

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

const next = document.querySelector('.carousel-control-next');
const prev = document.querySelector('.carousel-control-prev');
const images = document.querySelectorAll('.carousel-item');
const buttons = [next, prev];

buttons.forEach(el => {
  el.onclick = fadeIn
});
function fadeIn() {
  images.forEach(image => {  
    image.classList.add('fade-in');
    image.addEventListener('transitionend', (e) => image.classList.remove('fade-in'));
  });
}
.fade-in {
  -webkit-animation: fadein 4s;
  animation: fadein 4s;
}
@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-100" src="http://via.placeholder.com/350x150" alt="First slide">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="http://via.placeholder.com/350x150" alt="Second slide">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="http://via.placeholder.com/350x150" alt="Third slide">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</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

Optimal approach for incorporating controller As with UI Router

Currently working on a small search application using AngularJS and Elasticsearch. I am in the process of transitioning the app from using $scope to controller As syntax. I have implemented UI Router for managing routes/states. I have been attempting to us ...

unable to utilize react-speech-recognition package

Looking for a simple react package that can convert user audio to text? I recently installed one and tried its basic code example, only to encounter an error message stating "RecognitionManager.js:247 Uncaught ReferenceError: regeneratorRuntime is not defi ...

"Enhancing Code Functionality in React - Seeking Ways to Improve

When working with Redux, I often find myself repeatedly using the same piece of code: const dispatch = useDispatch() Then, every time I need to call a function, I do something like this: dispatch(endpointError(true)) My goal is to streamline this proce ...

Configuring a Meteor.js application requires defining variable scopes for templates in order to manage

Is there a way to define a variable that is limited in scope to a specific template? I want this variable to be accessible by multiple helpers within the template, but not outside of it. For example, how can the game variable be shared between two templat ...

Tips for invoking a .NET function from JavaScript in a Windows Phone Blank app

How can I invoke a .NET function from JavaScript within my Windows phone blank App? I am designing the user interface by parsing XML, and the function name is retrieved as a string from the XML. What is the best way to call this function? ...

Using the forEach method, we can create multiple buttons in ReactJS and also access the onClick handler

I have a button with both the label and onClick properties. Additionally, I have an array containing the values I need to assign to the label property. Here is the code snippet: render(){ {tabel_soal.forEach(function (item, index) { <Ra ...

How can we efficiently load a JSON file from a local path into an HTML document in a way that is compatible with all browsers?

I am attempting to retrieve JSON data from a local path and display it on a basic HTML page. I have tried various methods such as fetch, ajax in order to load the data and update the corresponding values on the web page. The goal is to host this page so t ...

Encountered the error message "Router.js file throwing a TypeError: next is not a function" while implementing navigation guards in my Vue 3 project

I'm puzzled as to why 'i' doesn't recognize the next function, even though I followed a similar video that implemented it without any errors. import Dashboard from "./Pages/Dashboard.vue"; import Customers from "./Pages/Customers.vue"; ...

Prevent the upward arrow from appearing on the first row and the downward arrow from appearing on the last row when

This is a straightforward question, but I'm unsure how to achieve it. I am currently working on sorting columns using jQuery. $(document).ready(function(){ $(".up,.down,.top,.bottom").click(function(){ var row = $(this).parents("tr:f ...

Java REST service remains out of reach for JavaScript fetch call

Currently, I am in the process of learning about REST API. My goal is to make a call to a POST service implemented in Java from Javascript using fetch. However, I have encountered an issue where the request fails to reach the service whenever the @Produces ...

Adding the number of occurrences to duplicates in a string array using JavaScript

Looking to append a count to duplicate entries within a string array. The array in question contains duplicates, as shown below. var myarray = ["John", "John", "John", "Doe", "Doe", "Smith", "John", "Doe", "Joe"]; The desired output shoul ...

Exploring ways to increase the width of rows in Bootstrap 4

Is there a way to make a row expand to 100% of its containing div in Bootstrap 4? I've tried using w-100 and d-inline-block but neither seems to work. Any help would be appreciated. CODEPEN .container { width: 90%; border: 1px solid black; h ...

Encountering an unrecognized error on Windows when attempting to execute a child process with regex return

Below is the code I am utilizing to retrieve Make file targets: const command = `make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\\/t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'`; cp.exec(command, options, (error, stdout, s ...

Store the visible image location in memory to be used across various sections

I'm currently developing a website with a scrolling background image feature. However, whenever I navigate to another page on the site, the animation restarts from the beginning. Is there a way to cache the position so that the animation continues sea ...

What is the method for showcasing an array using AngularJs in my specific scenario?

I have an array in JavaScript structured like this: var data = [ 2005 = [ Jan = [0,1,2,3,5...], Feb = [0,1,2,3,5...], ...more ], 2006 = [ Jan = [0,1,2,3,5...], Feb = [0,1,2,3,5...], ...more ], 200 ...

Exploring the capabilities of Three.js Projector and Ray components

Recently, I've been experimenting with the Projector and Ray classes for collision detection demos. My main focus has been on using the mouse to interact with objects by selecting or dragging them. While studying examples that utilize these classes, I ...

Tips for preventing the appearance of two horizontal scroll bars on Firefox

Greetings, I am having an issue with double horizontal scroll bars appearing in Firefox but not in Internet Explorer. When the content exceeds a certain limit, these scroll bars show up. Can someone please advise me on how to resolve this problem? Is ther ...

Tips for capturing audio in flac codec format using JS/AJAX

Is there a way to record audio in flac codec instead of opus codec? I attempted setting the codec to flac like this: let blob = new Blob(audioChunks,{type: 'audio/ogg; codecs=flac' }); I also tried this: var options = { audioBitsPerSecond : ...

Tips for incorporating an entire JavaScript file into a React JS project

I'm facing an issue with a .js file (JavaScript file) that lacks exports code, containing only a constructor and some prototype methods. I am trying to incorporate this file into my ReactJS App. My approach involved adding a script tag in client/inde ...

JavaScript Filtering Technique

Attempting to compose an array of names for a search output page The json arrangement looks like this: data = { "artists": [ { "artistName": "a" }, { "artistName": "b" }, { "artistName": "c" }, { "artistName": "d" }, { "artistName" ...