Looking for a way to make one image disappear briefly while transitioning to another image in Javascript

**Hey there, coding enthusiasts! I could really use some help right now. I am trying to create a smooth image transition effect using Javascript, where one image fades out while the next one fades in seamlessly. As someone who is still relatively new to programming and seeking guidance, how can I achieve this without any noticeable background changes?

I was hoping that the code would smoothly fade between images in a loop. Here is what I have managed to come up with so far.**

======HTML CODE=====

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Javascript Image Transition</title>
====CSS======

        <style>
            body {
                text-align: center;
            }
            h1 {
                color: green;
            }
    
            img {
                position: absolute;
                left: 400px;
            }
        </style>
    
    </head>
    <body>
        <div id="scroll-image">
    
        <img src="SnugBear_home.png" class="test"/> 
    
        <img src="img.png" class="test"/>
    
        <img src="img2.png" class="test"/>
        </div>
    
=======Javascript Code=======
        <script>
            startImageTransition();
    
            function startImageTransition() {
                
                var images = document.getElementsByClassName("test"); 
    
                for ( var i = 0; i < images.length; ++i) {
                    images[i].style.opacity = 1; 
    
                }
    
                var top = 1;
   
                var cur = images.length - 1; 
    
            setInterval(changeImage, 3000);    
    
            async function changeImage() {
    
                var nextImage = (1 + cur) % images.length;
    
                images[cur].style.zIndex = top + 1;
                images[nextImage].style.zIndex = top;
    
                images[cur].style.zIndex = top;
        
                images[nextImage].style.zIndex = top + 1;
    
                top = top + 1;
    
                images[cur].style.opacity = 1;
    
                cur = nextImage;
            }
                    function transition() {
                    return new Promise(function(resolve, reject) {
   
                        var del = 0.01;
    
                       
                        var id = setInterval (changeOpacity, 10);
    
    
            
                        function changeOpacity() {
                            images[cur].style.opacity -= del;
                            if (images[cur].style.opacity <= 0) {
                                clearInterval(id);
                                resolve();
                            }
                        } 
                }) 
            } 
        } 
        </script>
        
    </body>
    </html>

Answer №1

To achieve a fading effect, you can utilize CSS animations in your code. I found the snippet provided quite impressive and decided to enhance it with a simple `.animate()` code block.

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Image Transition Using Javascript</title>;

        <style>
            body {
                text-align: center;
            }
            h1 {
                color: green;
            }
    
            img {
                width: 100px;
                height: 100px;
                position: absolute;
                left: 400px;
            }
            
            #one {
              background-color: red;
              }
            #two {
              background-color: blue;
              }
            #three {
              background-color: green;
              }
        </style>
    
    </head>
    <body>
       <div id="scroll-image">
    
        <img src="SnugBear_home.png" class="test" id="one"/> 
    
        <img src="img.png" class="test" id="two"/>
    
        <img src="img2.png" class="test" id="three"/>
       </div>
    
        <script>
            startImageTransition();
    
            function startImageTransition() {
                
                var images = document.getElementsByClassName("test"); 
    
                for ( var i = 0; i < images.length; ++i) {
                    images[i].style.opacity = 1; 
    
                }
    
                var top = 1;
   
                var cur = images.length - 1; 
    
            setInterval(changeImage, 3000);    
    
            async function changeImage() {
    
                var nextImage = (1 + cur) % images.length;
    
                images[cur].style.zIndex = top + 1;
                
                images[cur].animate([
                {opacity: 1},
                {opacity: 0}
                ], 3000)
                images[nextImage].style.zIndex = top;
                images[nextImage].animate([
                {opacity: 0},
                {opacity: 1}
                ], 3000)
                images[cur].style.zIndex = top;
        
                images[nextImage].style.zIndex = top + 1;
    
                top = top + 1;
    
                images[cur].style.opacity = 1;
    
                cur = nextImage;
            }

            function transition() {
                return new Promise(function(resolve, reject) {
   
                    var del = 0.01;
    
                    var id = setInterval (changeOpacity, 10);
    
                    function changeOpacity() {
                        images[cur].style.opacity -= del;
                            if (images[cur].style.opacity <= 0) {
                                clearInterval(id);
                                resolve();
                            }
                        } 
                    }) 
                }
            } 
        </script>
        
    </body>
</html>

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

HTML: Accept only images in PNG, GIF, and JPG format for file upload

How can I customize the HTML upload dialog window to only show JPG, GIF, and PNG files when users upload an image? ...

Guide on sending a JavaScript variable as a URL parameter in Django

I need to pass a radio ID to my view, but I'm struggling with how to do it using the GET method in the URL: html: <a href="{% url 'maintenance_issue_fix' %}?radio_id=checked"> <img src="{% static 'images/ma ...

Is there a method available to minimize the size of a local storage list containing strings?

Hey there, I am trying to load a large 2.5MB json file in my browser so that I can use it for some typeAhead functions. Unfortunately, I'm facing an issue with my local storage being constantly full. When using Firefox, I receive the following error ...

Guide to sending back a promise using JQuery

Here is the Durendal code I am working with: var variable = ko.observable(""); function activate(){ return myModel.doSomething(variable); } The doSomething function looks like this: function doSomething(variable){ if(someCondition) return ...

Resolve the issue of autofill data overlapping with field labels

My form incorporates the Canada Post AddressComplete tool, which functions similarly to Google Maps Autocomplete. As you type your address, suggestions appear in a drop-down menu. However, after selecting an address, the text in the Postal Code and City f ...

Remove the color gradient for the column headers in the Google Visualization table

Whenever I attempt to change the colors of the column headers using the method demonstrated in this insightful source, a rather generic gradient is applied. Interestingly, the example code provided also demonstrates the same default gradient on the secon ...

Ways to navigate private property using the App Component in Angular 4

I have successfully implemented code in my app component to retrieve the current URL and display it in app.component.html. app.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Compone ...

The footer is anchored at the bottom on one page but mysteriously relocates to the center on the next page

I've been working on creating a footer for my Angular application and here's the code for it: // HTML <footer class="footer"> // code for footer </footer> // LESS .footer { position: absolute; bottom: 0; width: 100% ...

Utilize jQuery to dynamically add or remove elements by referencing specific HTML elements

My goal is to dynamically add an element to a dropdown menu and then remove it after selection. I initially attempted to define the htmlElement reference in this way: (Unfortunately, this approach did not work as expected) var selectAnOption = "<option ...

Create an HTML button with dual functionality

I currently have a button in my HTML that triggers the opening of the sidebar on mobile devices. <a href="#header" class="button scrolly">Contact Me</a> There is also a label element that, when clicked, selects the name field in the contact f ...

Creating a Mongoose schema to store an array of objects, where updates will automatically add new objects

const mongoose = require('mongoose'); module.exports = mongoose.model('GridModel', { Request_Id : { type : Number, required : true }, viewStudents : { type : Array , default : [] } }); The mongoose model above needs to b ...

How can I prevent my mouse click from being overridden by my mouse hover?

Currently, I am developing a Sudoku game using JavaScript and facing some challenges with mouse events. My goal is to enable users to hover over a square and have it change color, as well as click on a square to highlight the entire row, column, and quadra ...

My custom style sheet not taking precedence over Bootstrap styles

Using !important is something I try to avoid as much as possible. When I downloaded Bootstrap 3.0, I made sure to include the call to the .css file AFTER my core style sheet so that any changes I make to elements like .h1, h1{} take precedence over Bootstr ...

Is it possible to request/scrape pages from the client side?

Let me present the issue at hand: I am currently managing a web application that serves as a notification system which updates frequently. This application is operational on several local computers, each of which solely display information without any inp ...

steps to overlay an image over another in bootstrap:

I am trying to place an image over another image. Here is the code I have used: <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8> <meta name="viewp ...

The transparency level of materials in THREE.js

When using the lambert shader, I encountered an issue with setting the material. In the example provided, it sets the material as follows: this.material.uniforms.emissive.value = new THREE.Color( Math.random(), Math.random(), Math.random()); Prior ...

leveraging socket.io alongside express router

As someone who is relatively new to node.js, I am currently in the process of creating a webchat application. My project consists of a server.js file and a router.js file where I have defined all my routes. Unlike many others, I am not using express-genera ...

Retrieve an array field across various documents and combine the elements to form a single object

Consider a scenario where there is a users collection. Each user document includes an array of posts called posts. The goal is to query this collection as follows: Retrieve 2 posts, starting at index Nstart and ending at index Nend, from each user in the ...

What is the process for setting an object's property as a href in an AJAX call?

I've got a quick query. How can I assign an object's property to the href attribute? I've indicated the line with a comment. success: function (listOfTags) { let tagData = ''; $.each(listOfTags, function (i, tag) { ...

Differentiate various collections of shapes

My application has a specific workflow: 1) Next to the name of Patient X, there is a "Check In" button. Once clicked, this action is recorded on the server side. 2) Upon clicking the "Check In" button, a dropdown menu appears with various locations for t ...