Continuous animation for a sequence of overlapping images with smooth transitions

Currently, I am in the process of developing a JavaScript script that will cycle through a series of images within the same <div>. The goal is to create a seamless animation effect with the image transitions. Although the images are cycling through, the transition is not as smooth as desired.

var slideIndex = 0;

showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
    slides[i].style.opacity = "0";
  }
  
  slideIndex++;
  
  if (slideIndex > slides.length) {
    slideIndex = 1
  }
  
  slides[slideIndex - 1].style.display = "block";
  slides[slideIndex - 1].style.opacity = "1";
  setTimeout(showSlides, 2500);
  // Implementing a transition effect on the images.
  slides[slideIndex - 1].style.transition = "all 2.50s";
  // Introducing a delay for the images during transition.
  slides[slideIndex - 1].style.transitionDelay = "2.50s";
}
<div class="p-centered">
  <img src="https://picsum.photos/200?1" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?2" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?3" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?4" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?5" class="img-responsive mySlides" alt="">
</div>

Answer №1

Enhanced with proper pointer-events functionality

Take a look at this illustration utilizing display: grid to arrange the images in a stack.

The core structure of the original code remains intact, with some static styles being relocated to CSS for a more organized JavaScript codebase.

We trust that this example proves beneficial!

For instance:

var slideIndex = 0;
var slides = document.getElementsByClassName("mySlides");

// Static styles moved to CSS for cleanliness
showSlides();

function showSlides() {
  // Display current image
  slides[slideIndex].classList.add("active");     
  // Hide previous image
  const prevIndex = slideIndex === 0 ? slides.length - 1 : slideIndex - 1;
  slides[prevIndex].classList.remove("active");
  // Prepare index for next cycle
  slideIndex === slides.length - 1 ? (slideIndex = 0) : slideIndex++;
  // Set delay for next cycle
  setTimeout(showSlides, 2500);
}
.p-centered {
  display: grid;
  width: fit-content;
}

.mySlides {
  grid-area: 1/ 1/ 1 /1;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.50s linear;
}

.active {
  opacity: 1;
  pointer-events: auto;
}
<div class="p-centered">
  <img src="https://picsum.photos/200?1" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?2" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?3" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?4" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?5" class="img-responsive mySlides" alt="">
</div>

Answer №2

Utilize a single class that incorporates Opacity and Transition effects.

Employ JavaScript to activate the specified class.

I have optimized your JS code so that you no longer need to loop through all images each time to hide them.

var slides = document.getElementsByClassName("mySlides");
var slideIndex = 0;

// Initially show the first image
slides[0].classList.add("show");

setInterval(showSlides, 2500);

function showSlides() {
  // Hide current image
  slides[slideIndex].classList.remove("show");

  // Update index
  slideIndex++;
  if (slideIndex >= slides.length) {
    slideIndex = 0
  }
  
  // Show new current image
  slides[slideIndex].classList.add("show");
}
.p-centered {
  position: relative;
}

.mySlides {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: all 2000ms;
}

.mySlides.show {
  opacity: 1;
}
<div class="p-centered">
  <img src="https://picsum.photos/200?1" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?2" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?3" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?4" class="img-responsive mySlides" alt="">
  <img src="https://picsum.photos/200?5" class="img-responsive mySlides" alt="">
</div>

Answer №3

One approach to solving this issue is by maintaining all images with a display: block property and adjusting the opacity to create a fading effect continuously. Another option is to set the display: none property for images once they have completely faded out.

To make this method effective, the images should overlay each other. This can be achieved using the position: absolute property, assuming the containing element (the p-centered div) is manually sized. For example:

let slideIndex = 0;

function showSlides() {
  const slides = document.getElementsByClassName("slide");
  // Hide existing shown slides
  for (let i = 0; i < slides.length; i++) {
    slides[i].classList.remove('show');
  }
  // Show current slide
  slides[slideIndex % slides.length].classList.add('show');
  slideIndex++;
  setTimeout(showSlides, 2500);
}

window.addEventListener('load', showSlides);
.container {
  height: 274px; /* maximum image height */
}

.slide {
  position: absolute;
  opacity: 0; /* hide until `show` class */
  transition: opacity 0.5s;
}
.slide.show {
  opacity: 1;
}
<h1>Before Container</h1>

<div class="container">
  <img class="slide" src="https://www.wikipedia.org/portal/wikipedia.org/assets/img/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c4b7577756c7978757d3170737b73316a2e5c2d322964326c727b">[email protected]</a>">
  <img class="slide" src="https://www.wikiversity.org/portal/wikiversity.org/assets/img/Wikiversity-logo-tiles_1.5x.png">
</div>

<h1>After Container</h1>

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

Restricting Horizontal Scrolling in Dash DataTable with multi-tiered header (without any additional empty gaps)

I'm currently developing a Dash application using Plotly that showcases two tables, specifically dash_table.DataTable, each with multiple columns. The initial table features a multi-level header. For both tables, the first few columns are fixed while ...

Creating inner borders on a pie chart with HTML and CSS: A step-by-step guide

After putting my coding skills to the test, I successfully crafted a stunning pie chart using only HTML and CSS. https://i.sstatic.net/5xCbl.png Here's the code snippet I tinkered with: HTML - <div class="pie-chart"></div> CS ...

Enhancing Vue Filtered Lists for Increased Dynamism

Currently, I am iterating through a list of items using the v-for directive. Before displaying the list, I apply a filter based on a specific value using the .filter() method. To switch between different filtered values, I utilize the v-on:click event. How ...

Error message: "Ajax script is failing to run"

Currently I am delving into the world of Ajax and have encountered a minor issue. I've been attempting to make a POST request to a Django backend using ajax, but strangely enough, the alert isn't showing up on screen. Furthermore, upon inspectio ...

The issue of Google fonts failing to load on Windows browsers while loading perfectly on Mac browsers has been observed

Stackers. I am currently the Front End developer for www.PinionLMS.com. Our website is using "Lato," a Google font. The issue we are experiencing is that when you access the site from a Windows (8.1) browser such as Chrome, Firefox, or Internet Explorer ...

What is the method for specifying a JSON object within a DOM element's `data` attribute?

In an attempt to store JSON data within a dataset attribute, I encountered the following HTML structure: The appearance of the HTML is as follows <div data-switch="true" data-json="{'key1': 'value 1'}, {'key2': 'valu ...

What could be the reason my span is not altering color as I scroll?

Important HTML Knowledge <section class="home" id="home"> <div class="max-width"> <div class="home-content"> <div class="text-1">Hey t ...

Issue with fuse-box: unable to import ReactDOM

Recently, I decided to switch from webpack to fuse-box for my side project. Everything is compiling without any issues, but when I try to load it, an error pops up: I downloaded a React demo code and it works fine. Additionally, there are no problems wit ...

Converting Persian calendar date to Gregorian in JavaScript

Looking for assistance in converting a date from 1379/10/02 to AD format, specifically to the date 2000/4/29 using the momentJs library. Any help with this task would be greatly appreciated. Thank you! ...

Modifying website elements with JavaScript

Can someone assist me with getting a script to work on my website that will allow me to switch between four different sets of content using buttons labeled 1, 2, 3, and 4? I have tried using addClass and removeClass but cannot seem to get it right. Here i ...

Stretching Images on Circular Images - Utilizing Bootstrap and SCSS styling

Can anyone assist me with this problem? I am currently utilizing bootstrap cards to create a section on my website. However, I am encountering an issue with the circular images of the cards. I want to prevent my images from getting stretched when placed i ...

Parcel JS: The function tree.render is missing or not defined

Every time I attempt to execute the production build command npm run build or npx parcel build index.html, this error occurs. My project consists of simple HTML and CSS, without any React or third-party libraries. What could be causing this issue? I have t ...

Executing a jQuery AJAX request for a second time

Upon hitting the submit button for the first time, the codes work successfully. However, upon hitting the button for the second time with correct email and password values, nothing happens and the user cannot log in. I have identified that the issue lies w ...

Using Struts2 actions in combination with jQuery AJAX calls

Similar Question: How to utilize $.ajax() method in struts2 In simple terms: 1. Could someone explain how to trigger a struts action using jquery ajax? (without using the struts jquery plugin) 2. How do I retrieve results and display HTML output cor ...

Show or hide a fixed position div using jQuery when clicked

I am new to jQuery and I am trying to create a "full page menu" on my own. However, I am struggling to hide the menu on the second click. I tried using .toggle() but I found out that it has been deprecated. Can someone assist me with this? Thank you so muc ...

jmpress: Scrolling through Absolutely Positioned Element (Slide) with dynamic height

Check out the Live Site I'm currently working on a website using jmpress, but I'm facing difficulties in implementing scrolling functionality for my content. While I can scroll in Chrome by selecting text and dragging down, I want to achieve thi ...

Inquiries regarding real-time alerts and notifications

Just curious, I am wondering about the creation of those notifications/alerts (for example on platforms like twitchalerts, commonly used by livestreamers). Are they typically coded in JavaScript/AJAX or another language? Is there a specific framework for ...

Use VB.NET to dynamically update cell content in HTML

Can you assist me with updating cellContent in HTML using vb.net? The DataGrid view is on a website. Below is the inspected HTML: <div class="grid-controls"> <form method="post" class="vss-app-form grid-control-popover none" id="gridMorePopov ...

vue implementing autoscroll for long lists

I am looking to implement an autoscrolling log feature on my webpage that is dynamically fetched from a REST endpoint. To handle the potentially large size of this log, I decided to use vue-virtual-scroll-list. Additionally, I wanted the log to automatical ...

utilizing different background colors for rows in a Laravel table using CSS

Is there a way to implement alternate row coloring in a Laravel table using CSS? I want to have different colors for every other row. I have applied the "gridview" CSS class to the table. Specifically, I want to use the .gridview tr.even td selector for th ...