What is the best way to halt a CSS transition using JavaScript when dealing with an image?

I am facing an issue while attempting to create a basic CSS transition using JavaScript. The goal is for the start button to trigger the movement of an element, based on the duration of the keyframe animation. Then, clicking the end button should make the element disappear and reappear when the start button is pressed again with the same animation.

I'm not sure what is causing this problem. Additionally, after the transition ends, the element jumps to a corner unexpectedly.

function add()
  {
  document.getElementById("myAnimation").classList.add("run-animation");
  }    
function remove()
  {
document.getElementById("myAnimation").classList.remove("run-animation");
  }
body{
 background-color: "#4287f5";
}

#myAnimation
{
position:relative;
height: 40px;
width: 40p;
}
.run-animation 
{
-webkit-animation: move 6s;
    animation: move 6s;
}

@-webkit-keyframes move
{
 0%  {left: -200px;}
    25%  {left: 200px;}
    50%  {left: 100px;}
}
@keyframes move
{
0%  {left: -200px;}
    25%  {left: 200px;}
    50%  {left: 100px;}
}
 <button onclick="add()">Start</button> 
  <button onclick="remove()">End/Remove</button> 
 <div id="myAnimation" class="run-animation"><img src="https://cdn1.imggmi.com/uploads/2019/10/23/6e17286b0e01cf2775e6fa81a07d1ae3-full.png" /></div>

Answer №1

Instead of using an animation, consider implementing a "transition" for the effect you desire.

"Yeah but how do I make it go farther than the end point?" [someone might say.]

To achieve this, utilize a custom bezier-curve timing function with values outside the [0, 1] range to create a bouncing effect.

By controlling just one value, you can easily manage the two states of your element.

#myAnimation {
  height: 40px;
  width: 40px;
  background: red;
  transform: translate(-40px, 0);
  transition: transform 1.5s cubic-bezier(0, 0, 0.5, 3);
}
:checked ~ #myAnimation {
  transform: translate(100px, 0);
}
body{ margin:0; }
<input type="checkbox" id="check"><label for="check">show elem</label>
<div id="myAnimation"></div>

Note: In the above example, I used transform instead of left for better performance reasons. You can also use a button with JavaScript to toggle a class for the same effect.

Answer №2

It seems like the reason your element is not appearing correctly is because you haven't specified its default appearance when it's not being animated. Try setting display:none; as the default style and then change it to display:block; during the animation. Here's an example:

function add() {
  document.getElementById("myAnimation").classList.add("run-animation");
}

function remove() {
  document.getElementById("myAnimation").classList.remove("run-animation");
}
body {
  background-color: "#4287f5";
}

#myAnimation {
  position: relative;
  /*
  Hide the element if it is not animated
  */
  display: none;
  height: 40px;
  width: 40p;
}

#myAnimation.run-animation {
  -webkit-animation: move 6s;
  animation: move 6s;
  /*
  Show the element if it is animated
  */
  display: block;
}

@-webkit-keyframes move {
  0% {
    left: -200px;
  }
  25% {
    left: 200px;
  }
  50% {
    left: 100px;
  }
}
  
@keyframes move {
  0% {
    left: -200px;
  }
  25% {
    left: 200px;
  }
  50% {
    left: 100px;
  }
}
<button onclick="add()">Start</button>
<button onclick="remove()">End/Remove</button>
<div id="myAnimation" class="run-animation"><img src="https://cdn1.imggmi.com/uploads/2019/10/23/6e17286b0e01cf2775e6fa81a07d1ae3-full.png" /></div>

Answer №3

Perhaps this solution could be beneficial

function add()
  {
  document.getElementById("myAnimation").classList.add("run-animation");
  }    
function remove()
  {
document.getElementById("myAnimation").classList.remove("run-animation");
  }
body{
 background-color: "#4287f5";
}

#myAnimation
{
position:relative;
height: 40px;
width: 40p; 
    left: 0;
    opacity: 1;  
}
.run-animation 
{
-webkit-animation: move 6s;
    animation: move 6s;
    animation-fill-mode: forwards;
}

@-webkit-keyframes move
{
0%  {left: 0;}
    25%  {left: 200px;opacity: 1;}
    50%  {left: 100px;opacity: 0;}
    80%  {left: 0; opacity: 0;}
    100% {left: 0; opacity: 1;}
}
@keyframes move
{
0%  {left: 0;}
    25%  {left: 200px;opacity: 1;}
    50%  {left: 100px;opacity: 0;}
    80%  {left: 0; opacity: 0;
    100% {left: 0; opacity: 1;
    
}
<button onclick="add()">Start</button> 
  <button onclick="remove()">End/Remove</button> 
 <div id="myAnimation" class="run-animation"><img src="https://cdn1.imggmi.com/uploads/2019/10/23/6e17286b0e01cf2775e6fa81a07d1ae3-full.png" /></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

Displaying divs depending on dropdown selection - Troubleshooting script issue

When I try to display certain divs based on dropdown selection using the script below, it works fine on a simple page. However, when I implement it on my current development page, it completely messes up the layout, turning everything black and adding stra ...

Unable to load models in face-api.js even though attempting to infer the models

Currently, I am working on developing an application for face detection. However, I am encountering an error stating "SsdMobilenetv1 - load model before inference" despite loading the models. The Front End HTML File is being sent from the server, ...

Incorporating a stationary navigation bar alongside a parallax scrolling layout

After spending the entire night trying to figure this out, I have had zero success so far. I decided to tackle this issue with javascript since my attempts with CSS have been completely fruitless. This is a demonstration of the parallax scrolling webpage. ...

Steps for displaying a loading gif animation prior to retrieving text content using JavaScript

Before fetching the PHP result, I want a loading GIF image to display within the div section. <!DOCTYPE html> <html> <head> <title> CTR Calculator Tool | Free Click Through Rate Online Calculator </title> & ...

Setting up GameClosure on a Windows machine

Is it possible to install GameClosure on Windows? The installation guide mentions that only OSX is officially supported, but there have been reports of success running it on Linux and Windows. However, the process for doing this is not well-documented. A ...

Ways to implement a percentage for scrollTop

I'm currently troubleshooting the code below. My goal is to understand why I'm unable to scroll the .post div with jQuery and input range properly using a percentage value like this: $("[type=range]").on('input',function(){ var v ...

What is the reason behind Intellij Code Inspection indicating that a selector is not being used?

I have a small project consisting of two files located in the same folder. App.css .App-align-left { text-align: left; } App.js import React from 'react'; import 'App.css'; class App extends React.Component { constructor(p ...

Testing React Component State Updates

I've been dedicated to achieving close to 100% unit test coverage with my React application, focusing particularly on the useAsync hook. I came across a code snippet from react hooks: import { useState, useEffect, useCallback } from 'react'; ...

The Spring Boot REST application is unexpectedly returning HTML instead of JSON, causing confusion for the Angular application which is unable to recognize the

I am struggling with my Spring Boot application that was generated using . I am having difficulty getting it to return JSON instead of HTML. Here is a snippet of the code: [@CrossOrigin(origins="http://localhost:4200",maxAge=3600) @RestController @Request ...

Prevent running function bodies simultaneously based on user events in JavaScript until a previously triggered execution is completed

When a user clicks on a button in my component, the doSomething function is activated. The issue I am facing is that doSomething takes between 200-1100ms to finish execution and change state. What complicates matters is that when the button is clicked rapi ...

EaselJS BitmapAnimation has delay when using gotoAndPlay

I have created a requirejs module that enhances the functionality of a BitmapAnimation by allowing it to move around the stage at a specific speed and transition to another looped animation once reaching its destination. The issue I am encountering is a n ...

Rendering HTML with Apache Tiles using an empty <a></a> tag

Having encountered a peculiar issue with HTML lately. In my backend, the problematic section looks like this. <div class="content"> <a href="detail.html"></a> <img src="assets/i ...

Failing to reach the nested if statements within a switch case block

Before removing my question, please read this. Despite testing with console.logs, my code does not enter the if statements. I have not come across a similar solution to my issue. In an attempt to address any timing or asynchronous problems, I added a use ...

Selenium is throwing an ElementNotInteractableError indicating that the element is not able to be

Today I decided to dive into learning Selenium, but I've hit a roadblock while trying to click on an element that looks like this: <a rel="nofollow" style="" href="javascript:void(0);" time="" itemid="15 ...

Laravel: Issue with displaying stored images from the database

When using Laravel, I encountered an issue where the stored image from the database is not displaying: Even though $post->image has the location posts/1lSBv7Ana8Lonj9Au37IrujjnnEaYgzNWyamch33.jpeg, the image does not show up. The code snippet in index ...

Navigating through nested promises can be a daunting task within the world of JavaScript and Angular

Function 2 relies on the return of Function 1, while Function 3 uses both returns. How can I clean up this process? Currently, Function 3 is only giving me undefined values. Below are my 3 functions: Function1 $scope.nombreCompetencesATraiter = function ...

Display the field names from a MySQL table on a web page

Is there a way to show all column names from a MySQL table on a webpage if only the table name is known? ...

I am having trouble getting the bootstrap link and css files to work on a specific URL. Can you please help me troubleshoot this issue and let me know if there are any additional files needed to

When attempting to apply the bootstrap link and css files to the URL "/list/:customListName", they are not working. However, changing the URL to "/:customListName" somehow makes it work. What is the reason behind this behavior and how can I properly style ...

What is the best method to retrieve a global variable from two separate PHP files?

Within file1.php, there is a variable: global $name; $name = ""; In the same directory, within file2.php, there is: <label> <span>Username:</span> <input id="name" type="text" name="username" value ="<?php echo $GLOBALS[& ...

Apply a specific class to a list once scrolling beyond a certain offset of a group of division elements

I seem to be getting close, but I'm struggling to finalize this task. Essentially, as you scroll down to each image, the div containing that image's offset from the top of the window (with a buffer of -500) should add a .selected class to the cor ...