How can I incorporate a Slide-in Transition Effect for an Image when the img src is updated?

The image tag in my .HTML file looks like this:

<img id="xyz"/>

Within the JavaScript portion, I have the following code:

let i = 1;
let images = ["src1", "src2", "src3", "src4", "src5"];

let imgDiv = document.getElementById('xyz');
imgDiv.src = images[0];

setInterval(() => {
    momentDiv.src = images[i];
    i++;
    if(i == images.length) i=0;
}, 5000);

The image within imgDiv is now switching every 5 seconds.

How can I add animation or transition to the image when the "src" property changes?

Please provide a solution without using jQuery.

Answer №1

Unfortunately, achieving the desired result in this manner is not feasible.

In order to create a slide effect, you must have a minimum of 2 images. You will need to update the source of your second image and position it above the first image. The second image should then become the new first image (copying the source of the old second image to the original image tag and repeating the algorithm).

let i = 1;
let images = ["https://picsum.photos/200/200/?image=663", "https://picsum.photos/200/200/?image=662", "https://picsum.photos/200/200/?image=661", "https://picsum.photos/200/200/?image=660", "https://picsum.photos/200/200/?image=659"];

let imgDiv = document.getElementById('xyz');
let imgSecond = document.getElementById('zyx');

imgDiv.src = images[0];

setInterval(() => {
    imgSecond.src = images[i];
    imgSecond.classList.add('active');
    i++;
    if(i == images.length) i=0;
  
    setTimeout(function() {
      imgDiv.src = imgSecond.src;
      imgSecond.classList.remove('active');
    }, 1500); // the same time as transition animation at css.
}, 2000);
.wrap {
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
}

.wrap > img {
  position: absolute;
  top: 0;
  left: 0;
}

.wrap > img#zyx {
  top: 200px;
}
.wrap > img#zyx.active {
  top: 0;
  transition: top 1.5s;
}
<div class="wrap">
  <img id="xyz" width="200" height="200"/>
  <img id="zyx" width="200" height="200"/>
</div>

We sincerely hope that this guidance proves beneficial to you.

Answer №2

If someone is still looking for an easy way to achieve a fade in and out effect (you can also add other effects), here's how you can do it:

const images = ["img1_url","img2_url", "img3_url", "img4_url"];

$(function () {
    let i = 0;
    $("#id_of_the_img_element").attr("src", images[i]);
    setInterval(function () {
        i++;
        if (i == images.length) {
            i = 0;
        }
        $("#id_of_the_img_element").fadeOut("slow", function () {
            $(this).attr("src", images[i]);
            $(this).fadeIn("slow");
        });
    }, 2000);
});

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

The find functionality in Angular and Firebase seems to be malfunctioning

enter image description here Whenever I try to find the ID and data set is not set on these fields, I encounter an error in my console. The following code snippet displays the find expense code: import { Component } from '@angular/core'; import ...

In the past, I've crafted buttons and other elements using Photoshop, and subsequently saved them for web use. However, I'm now contemplating whether it's more advantageous to employ CSS in

In the past, I have utilized Photoshop to create visually appealing buttons and footer bars for my websites. However, I'm now pondering if it's more beneficial to utilize CSS for button creation. I've noticed that manually coding them can re ...

Implementing a Dynamic Navigation Feature using PHP in a Standalone File

I am currently working on creating a dynamic PHP navigation system that should highlight the active tab, but I'm facing challenges with making the active tab part function properly. While there are simpler methods available, they all involve incorpora ...

The iOS website won't fully load until the button is tapped two times

- (IBAction)saveButton:(id)sender { NSURL *yourWebURL = [NSURL URLWithString: webpageURLLabel.text ]; NSURLRequest *webRequest = [[NSURLRequest alloc] initWithURL:yourWebURL]; if ([self checkIfValidURL] == YES) { [webpagePreview loadReq ...

invoking a Java servlet via JavaScript

Looking to develop a web application following the MVC design pattern. I am planning to use JavaScript for the GUI and Java Servlets for the controller. As someone new to JavaScript, I'm struggling to understand how to invoke a Java Servlet from Java ...

What steps should I take to show my JavaScript WhatsApp icons once more?

I have been running my website for 3 years now. It was built using HTML, CSS, and JavaScript, and I created it myself. There used to be a WhatsApp icon at the bottom right corner of the site, but it disappeared about 6 months ago. I checked my code and the ...

What is the best way to update the text of an <a> element when it is clicked

On my WordPress site, I've implemented a unique custom anchor button: <a class="add-to-cart-button">Buy Now</a> I'm interested in making the button text change when it's clicked. Could this functionality be achieved using java ...

Placing two images next to each other with accompanying captions

Currently working on developing a webpage, I am aiming to have two images in each row with captions positioned beneath them. The images are already configured as follows, I just require the captions: <div class = "container"> <img class = "pi ...

Programmatically extracting a list of utilized CSS images from IE WebBrowser (IHTMLDocument2)

Exploring the IHTMLStyleSheetsCollection, IHTMLStyleSheet, IHTMLStyleSheetRulesCollection etc. of IHTMLDocument2 to compile a list of all styles in the current document is quite simple. Does anyone have any suggestions on how to generate a list of only th ...

The functionality of Three.js arc drawing in canvas renderer seems to have encountered issues on Chrome

Looking at this example from the library, it is clear that the circles are adjusting their line width and appear thin when they are in close proximity. This functionality used to function properly. Currently, I am using Chrome version 27.0.1453.93 on OSX ...

Tips on aligning multiple elements vertically in a justified manner

I'm struggling to articulate what I need, but I'll give it a shot. I want to vertically align three different elements, each wrapped in their own divs. This is my current code: .service_info { margin-top: 45px; clear: both; ...

Converting a JavaScript object into HTML output

I have received the following JSON data: [    {       "fields": {          "url": "http://www.domain_name.co.uk/MP3/SF560783-01-01-01.mp3\n",          "track_name": "Lion City ",          "release_id": 560783,    ...

Display the final submenu of the Asp.net menu on the right side

The asp.net menu on my website is functioning properly with one exception: the last submenu does not change direction from left to right, and its content is getting cut off at the edges of the screen. This issue is particularly noticeable in the Master pa ...

What is the best way to adjust the body margin when using fixed navigation bars?

Currently, I am trying to set up the layout for my application. The existing layout works fine, but the issue is that the navigation bar does not stay fixed in position. Additionally, if the content exceeds a certain height or width, it should be controlle ...

Break big files into pieces and upload them incrementally with nodejs

I'm currently working on a project that involves uploading very large files in chunks to a server. The functionality on the server side is running smoothly, but I've encountered an issue with the client-side code. My approach so far has been to a ...

What steps do I need to take for webpack to locate angular modules?

I'm currently in the process of setting up a basic application using Angular 1 alongside Typescript 2 and Webpack. Everything runs smoothly until I attempt to incorporate an external module, such as angular-ui-router. An error consistently arises ind ...

Confirming the existence of a folder with AngularJS

Currently, I am attempting to determine if a folder exists so that I can make decisions on which files to include using ng-include. This is what I have so far: $scope.isVisible = { buttons: checkForClientOverwride('buttons'), it ...

Tips for aligning an image within a CSS-created bar graph

Would it be possible to position an image inside each bar of a bar graph without changing the bar's size? I've figured out how to do this with text, but not with an image. Alternatively, would it be better to place the image to the left of each b ...

I'm struggling to make this background show up in a div

Anyone able to help me figure this out? I can't seem to get the achtergrond_homepage.png as a background in rounded corners. Edit: It seems like the gray color is always on top. Could it be controlled in the JavaScript part? This is the CSS: @ch ...

Tips for utilizing Jquery webcam on mobile devices like Android and iPhone

Currently, I am in the process of developing mobile web applications utilizing jquery mobile and HTML 5. I am working on a feature that requires access to the camera. In order to achieve this functionality, I have integrated the following plugin: While ...