Creating a dynamic effect with JavaScript: Transitioning background images with a fading effect

I need help smoothing out the transition between three images that my divs switch between in a web animation. How can I implement a fade effect right before the switch happens?

<div class="my-images">
   <div id="image-1"></div>
   <div id="image-2"></div>
</div>


<script>
  function displayNextImage() {
     x = (x === images.length - 1) ? 0 : x + 1;
     document.getElementById("image-1").style.backgroundImage = images[x];
     document.getElementById("image-2").style.backgroundImage = images[x];
  }

  function startTimer() {
     setInterval(displayNextImage, 10000);
  }

  var images = [],
  x = 0;
  images[0] = "url('images/snow.jpeg')";
  images[1] = "url('images/nike.jpeg')";
  images[2] = "url('images/motor.jpeg')";
</script>

It's important to note that this animation loops continuously, so the fading effect should not be visible only on the initial load.

Answer №1

It is important to consider cross-browser compatibility when working without JQuery. Using JQuery can help you avoid these issues and achieve your desired results.

<div class="my-images">
   <div class="my-image" id="image-1"></div>
   <div class="my-image" id="image-2"></div>
</div>


<script>
  function displayNextImage() {
    $("#image-" + x).css('backgroundImage',  images[x]).show('slow');
    x++;
  }

  var images = [],
  x = 0;
  images[0] = "url('images/snow.jpeg')";
  images[1] = "url('images/nike.jpeg')";
  images[2] = "url('images/motor.jpeg')";
</script>

To ensure proper styling, make sure to add the following CSS:

.my-image{
  display:none;
}

If you do not use display: block, modify your CSS as follows:

.my-image{
  display:whatYouWant;
}

Don't forget to include the document ready() function and change show() to fadeIn():

$(document).ready(function(){
    $(".my-image").hide();
  });

  function displayNextImage() {
    $("#image-" + x).css('backgroundImage',  images[x]).fadeIn('slow');
    x++;
  }

This modification using fadeIn() will retain the previous value for a smoother transition.

If you want the div to be visible before adding an image, adjust the displayNextImage() function accordingly:

function displayNextImage() {
  $("#image-" + x).hide().css('backgroundImage',  images[x]).fadeIn('slow');
  x++;
}

Answer №2

If you want to achieve this with CSS animation, follow these steps for each cycle:

1) Change the image sources as you are currently doing

2) Restart the fade-in animation, read more here

3) Increment the index value

const images = [
  'https://source.unsplash.com/iMdsjoiftZo/100x100',
  'https://source.unsplash.com/ifhgv-c6QiY/100x100',
  'https://source.unsplash.com/w5e288LU8SU/100x100'
];

let currentIndex = 0;

const oldPic1 = document.getElementById('oldImage1');
const newPic1 = document.getElementById('newImage1');
const oldPic2 = document.getElementById('oldImage2');
const newPic2 = document.getElementById('newImage2');

window.setInterval(() => {
  // Replace new image with the old one
  oldPic1.src = newPic1.src;
  oldPic2.src = newPic2.src;
  
  // Set a new image
  newPic1.src = images[currentIndex];
  newPic2.src = images[currentIndex];
  
  // Reset the animation
  newPic1.style.animation = 'none';
  newPic1.offsetHeight; /* trigger reflow */
  newPic1.style.animation = null; 
  newPic2.style.animation = 'none';
  newPic2.offsetHeight; /* trigger reflow */
  newPic2.style.animation = null; 
  
  // Update the index
  currentIndex = currentIndex + 1 >= images.length ? 0 : currentIndex + 1;
}, 1500);
.wrapper {
  position: relative;
  top: 0;
  left: 0;
  float: left;
}

.oldPic1 {
  position: relative;
  top: 0;
  left: 0;
}

.newPic1 {
  position: absolute;
  top: 0;
  left: 0;
}

.oldPic2 {
  position: relative;
  top: 0;
  left: 100;
}

.newPic2 {
  position: absolute;
  top: 0;
  left: 100;
}

.fade-in {
  animation: fadein 1s;
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}
<div class="wrapper">
  <img id="oldImage1" class="oldImage1" src="https://source.unsplash.com/ifhgv-c6QiY/100x100" />
  <img id="newImage1" class="newImage1 fade-in" src="https://source.unsplash.com/w5e288LU8SU/100x100" />
</div>
<div class="wrapper">
  <img id="oldImage2" class="oldImage2" src="https://source.unsplash.com/ifhgv-c6QiY/100x100" />
  <img id="newImage2" class="newImage2 fade-in" src="https://source.unsplash.com/w5e288LU8SU/100x100" />
</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

How can I trigger an event to append a UL element using

Can anyone suggest a more elegant solution for handling an append/remove event from an element without having to manually trigger an event or resorting to other methods? It would be great if there was a way to do something like this: $('#id').o ...

Building a JavaScript module worker: Step-by-step guide

I am currently facing challenges with implementing web workers in my program. The example provided here is a simplified version of the code structure. There are 4 key files involved: index.html <!DOCTYPE html> <html> <head> <me ...

The accuracy of getBoundingClientRect in calculating the width of table cells (td)

Currently, I am tackling a feature that necessitates me to specify the CSS width in pixels for each td element of a table upon clicking a button. My approach involves using getBoundingClientRect to compute the td width and retrieving the value in pixels (e ...

Testing for packet loss using JavaScript

Do you know if there is a method in JavaScript to determine packet loss from the client side using AJAX, XMLHttpRequest, or any other approach? Your assistance is greatly appreciated. ...

Guide to dynamically adding content to a React component during rendering

While I initially thought that using the document object to dynamically create elements in vanilla JavaScript was a good idea, further research has shown me that this is not the preferred method when working with React. Can someone help me understand how t ...

I am facing an issue with my React JS component where it is only able to update the first time I click on a row in

I am encountering an issue with my list where the detail view is not updating when I click on a new row. This is happening after the first click, and as a beginner, I am unsure of how to resolve this. My detail component, named "UpdateSupp," contains the f ...

Tips for effectively removing objects from a PixiJS application

I have embarked on a game development project using Pixi.js that involves items falling from the top of the canvas. The functionality I've implemented so far allows items to spawn and move down the canvas until they reach the end of the window, at whi ...

The slider causing conflicts with widgets and content positioned below it in an HTML layout

When implementing a slider with a fade effect, there seems to be an issue with the placement of widgets on the homepage. The problem arises from the margin-top setting as when images change in the slider, the widgets clash with the slider. During the trans ...

Adding an element and updating its innerHTML can be achieved without relying on jQuery. Let's look at how this can be

I have a specific script that currently presents a list in alphabetical order. The list includes items like Apple, Banana, Blackberry, Blueberry, Cherry, and Cranberry. However, I would like to reorganize this extensive list, which consists of nearly 100 i ...

React-Native introduces a new container powered by VirtualizedList

Upon updating to react-native 0.61, a plethora of warnings have started appearing: There are VirtualizedLists nested inside plain ScrollViews with the same orientation - it's recommended to avoid this and use another VirtualizedList-backed container ...

Is there a way to incorporate a background image fadeIn effect for ul using CSS3?

I have a list on my webpage where each item is displayed with a CSS3 rotate animation. After the animation finishes, I want to set a background image with a FadeIn effect. To achieve this, I created a "addbg" class for the ul element like so: ul.addbg{ ...

How can you reposition a component within the dom using Angular?

Just started learning Angular, so I'm hoping this question is simple :) Without getting too specific with code, I could use some guidance to point me in the right direction. I'm currently developing a small shopping list application. The idea i ...

MongoError: What to do when the pipeline needs text score metadata, but no text score is provided?

When I run the following command directly in MongoDB 3.6.6 shell, I encounter an error that says "pipeline requires text score metadata, but there is no text score available." I'm not sure where to begin troubleshooting this issue. Here's how I ...

Scraping data from a webpage using Node.js and the Document Object Model

I am attempting to extract information from a specific website using Node.js. Despite my best efforts, I have not made much progress in achieving this task. My goal is to retrieve a magnet URI link which is located within the following HTML structure: < ...

Controller function not being triggered by ng-click directive

I'm currently working on an Ionic app and trying to use ng-click to call a function from my controller. Below is the function I want to call: function startSpin() { if ($scope.wheelSpinning == false) { spinWheel.animation.spins = 9; ...

What could be causing the border around my three.js canvas?

I'm utilizing a version of this code on my website and I have customized it to have a transparent background with only particles visible on the webpage. However, I've noticed a thin border around the canvas where these particles are displayed, ap ...

Using Vue to store form elements inside a component and accessing the data

Can someone help me decide if my approach makes sense? I may have gone overboard with components and now I'm questioning the benefits. I've created separate components for both the input field and send button in a form, but I'm facing challe ...

Solutions for resolving the error "Unable to access property 'value1' because it is undefined"

constructor() { super(); this.state = { value1 : Math.floor(Math.random() * 100), value2 : Math.floor(Math.random() * 100), value3 : Math.floor(Math.random() * 100), proposedAnswer : Math.floor(Math.random() * 3) + this.state.value1 + t ...

Repeatedly triggering the Jquery Dialog Event

When I open a calendar plugin in jquery dialog, I encounter a recurring issue. Every time I close and reopen the dialog, my calendar event onDayClick triggers multiple times – twice, thrice, and so on. <div id="show_calendar"> <div class="c ...

JavaScript method that accepts two functions as arguments

What is the proper syntax for passing two or more functions to a method, like in this example setInterval("javascript function",milliseconds); is the following correct? setInterval("pushmarkers();clearOverlays();loadmarkers();",5000); ...