Animate an image element to smoothly slide in from the left while simultaneously fading into view using Javascript

I'm looking to achieve a specific effect using pure JavaScript, HTML, and CSS without the need for jQuery or other libraries. I want an element to fade in and smoothly move to the center of the page from the left after a button click event.

My attempt so far is as follows:

if(selected_property[0] == 1 && selected_property[1] == 1) {
    var left = 0;
    setInterval(function(){
        left = left + 0.05;
        document.getElementById("property1_img").style.left = left + "vw";
        document.getElementById("property1_img").style.visibility = "visible";
    }, 1);
} else {
    
}

Answer №1

Forget about complicated animations - let CSS transitions do the work for you! It's much simpler than creating custom animation effects.

All you need to do is set up a JavaScript event handler for a click that updates the CSS .classList of the img element and utilizes CSS transitions for smooth animation.

let img = document.querySelector(".fadeMove");
document.querySelector("button").addEventListener("click", function(){
  img.classList.add("moved"); // Simply add the class to trigger opacity and position changes
});
/* Initial styling moves the element out of view to the left and makes it transparent */
.fadeMove {
  position:absolute;
  opacity:0;    /* fully transparent */
  left:-150px;  /* Off-screen to the left */
  
  /* 
     Specify that any numerical properties can transition smoothly over 2 seconds 
  */
  transition:all 2s;  
}

/* Additional style applied when button is clicked */
.fadeMove.moved {
  left:calc(50% - 75px); /* Centered on screen (for 150px wide image) */
  opacity:1;             /* fully opaque */
}
<img class="fadeMove" src="https://via.placeholder.com/150C/">
<button>Click</button>

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

Centering Slides Vertically in Slick Carousel with Bootstrap 4 Beta

I have spent approximately 2 hours searching and attempting over 15 solutions, but none of them have been successful. The issue involves a slick-slider structured as follows: <section id="testimonial-section" class="pt-4 pb-0 px-4 bg-dark text-white"&g ...

Video playback disabled on hover in Chrome browser

I have added videos to a search results page. When the user hovers over the video, I want to show a preview of it in a separate container and start playing the video. $(".videoSearchResults video").mouseenter(function () { var container = document.cre ...

Pictures are loading fine on a Chrome tab, but are showing a 403 error in the React code

I've been working on a React project that includes images using the img tag. Some of these images are failing to load with a 403 error: https://i.sstatic.net/AmgkF.png Interestingly, these same images load perfectly fine in another tab on Chrome: h ...

The initial rendering of the NextJs 13 application is experiencing significant sluggishness when deployed on an EC2

After deploying my NextJS 13.4 app on an AWS EC2 instance with 2 GB of RAM, I noticed that the initial load time is quite slow, taking around 20 seconds to load for the first time. The development mode in NextJS builds and displays the result, which may co ...

Injecting dynamic content using JavaScript

My goal is to develop a web page where clicking on any of the three images will cause the content to be inserted into the empty div located above the image links. Below is the JavaScript code I'm using: <script type="text/javascript" src="js/jque ...

Mysterious source utilizing leafletView for showcasing popups within the Angular Leaflet Directive

I've been attempting to implement a pop-up window on an Angular Leaflet map using Prune Cluster, but I keep running into an error stating that 'leafletView' is an unknown provider. Despite following the examples provided on this page, https: ...

Leverage the power of Next.js Dynamic routing query object with an SWR fetch request

While working with Next.js dynamic routing, I am facing an issue where my SWR fetch request is being called before the query object is properly set. This occurs specifically when using the routing query object. Let's take the example of a dynamic rou ...

What is the best way to set a value for a specific column using JavaScript in a RadGrid?

One of my requirements involves having a Radgrid where all rows are always in edit mode. Specifically, I am looking to implement a functionality in one of the columns where after an item is edited, all rows in that column should take on the same value. Her ...

Add a CSS and jQuery hover effect to display text over an image, requiring users to click twice on their mobile device

I have a bunch of panels for different categories that change the background image when hovered over, display some introductory text, and lead to a URL when clicked. However, on mobile devices, you need to tap the panel twice to activate the URL. What I&a ...

Choose all of the IDs from various sections using Jquery

I am facing an issue with having 2 identical IDs inside 2 separate sections. When the button is clicked, I want it to select the ID within this section and apply a style, then also select the ID in the other section and apply that same style. The code sni ...

Is it possible to incorporate shadows on a pie chart using recharts?

Does anyone know how to enhance a pie chart with shadows using the recharts library? https://i.sstatic.net/JLGVF.png https://i.sstatic.net/f5qv4.png If you have any solutions, please share. Thank you! ...

Adjust the brightness of a specified oklch color by 50% using CSS oklch(from ...) in combination with the calc() function

We have implemented a design system that includes various CSS custom properties for colors. For example: :root { --color--blue-1: oklch(88.6% 0.023 238); } Our latest addition is the utilization of the oklch color format. Currently, I am tasked with ca ...

Tips on adjusting section height as window size changes?

Working on a website that is structured into sections. Initially, all links are aligned perfectly upon load. However, resizing the window causes misalignment issues. Check out my progress at: karenrubkiewicz.com/karenportfolio1 Appreciate any help! CSS: ...

What is the best way to incorporate six rows of paragraphs using bootstrap?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" con ...

Challenges with conditional statements in JavaScript

This is a simple code snippet for a ToDo-List application. The function InputCheck() is designed to validate if the input bar contains any value. If the input bar is empty, the function should not trigger the addTodo function. However, in its current stat ...

Integrating a sleek Bootstrap 5 search bar drop-down functionality

As a newcomer, I could use some assistance with creating a dropdown menu that includes a search bar. Specifically, I want users to be able to select items from a list of foods or search for them. Unfortunately, I haven't been able to find a bootstrap ...

Return a string to the client from an express post route

I'm attempting to return a dynamically generated string back to the client from an Express post route. Within the backend, I've set up a post route: router.post('/', async (req, res) => { try { // Here, I perform computations on ...

Angular's input event fails to trigger for dynamically generated fields when pasted into them

When working with a form that has dynamically generated input fields, I encountered an issue. I needed to display a preview of the input contents on a div while pasting content into the fields. This project is built using Angular 11. Below is my .ts file: ...

An unusual problem stemming from jQuery/AJAX arises when variables within a function fail to update while a click

I've been struggling with a small issue for the past three days that I just can't seem to resolve. It doesn't seem to be a coding error, but rather a misunderstanding of variables and why the onClick event isn't functioning properly. H ...

When incorporating reduce into your code, remember to expect an undefined

Imagine you have an array like this: const novels = [ { id: 1, name: 'The Da Vinci Code', genre: 'Mystery', author: { name: 'Dan Brown', birthYear: 1964, }, releaseYear: 2003, }, { ...