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

Implementing an API call using Redux Saga within a React application

I have been diving into learning saga by following a tutorial on Medium and trying to implement it in StackBlitz. I encountered a path issue initially, managed to fix it after several attempts, but now a different problem has come up. Despite searching on ...

Determining the Height of a Navigation Bar Automatically with CSS

My website is built using React and react-strap. I set up my .header-overlay to cover the entire background within the .header. However, due to the presence of the .navbar, the .header-overlay extends beyond the boundaries of the .header vertically. I tho ...

Attempting to showcase JSON response within an HTML page using JavaScript

Can anyone help me troubleshoot my code for displaying JSON data on a web page? Here's what I have so far: <button type="submit" onclick="javascript:send()">call</button> <div id="div"></div> <script type="text/javascript ...

Different ways to swap table cells using only CSS

Does anyone know how to switch the positions of table cells using only CSS? I have three divs set up like this: #content { width: 1000px; display: table; float: none; vertical-align: top; border: 1px solid red; } #left { float: left; } #ri ...

The cloud function in Firebase was unable to connect to the dialogflow route

I am currently working on creating a chatbot using Dialogflow integrated with OpenAI in Firebase Cloud Function. However, I am facing an issue where I cannot access the /dialogflow endpoint and keep receiving the error message: "Cannot GET /dialogflow". My ...

Customizing the color of buttons in MUI 4

Currently, I am utilizing mui V4 for my styling and attempting to incorporate an additional color for my buttons. I understand that it only accepts these predefined colors: expected one of ["default", "inherit", "primary", "secondary"]. To achieve this, I ...

Show an item in a visual format of a list

Need help displaying a specific object: cars: { number': 1, 'overload': 1,'brand': {'0': {'porsche': [{'price': 10, 'id': 0}],'vw': [{'price': 20, 'id': 1}] ...

Is there a guarantee that XHR requests made within a click handler of an anchor tag will always be sent?

I'm trying to find information on whether an XHR request triggered in an anchor tag's click event handler is guaranteed to be sent. Despite my attempts at searching, I can't seem to locate a definitive answer. The specific question I have i ...

Invoke the designated JavaScript function within a subordinate <frame>

Below is an example of the standard HTML structure for a parent page named "index.html": <html> <head> <title>test title</title> </head> <frameset cols="150,*"> <frame name="left" src="testleft.html"> ...

Customizing the appearance of a date input field by passing an object with Vue.js

I created a dynamic table using Vuejs, where each cell contains an input element set as readOnly initially. The table also includes an 'edit' button for each row, which, when clicked, changes to 'save' and allows editing of the input el ...

React JS tutorial: deleting an entry from the browser's localStorage

I am currently working on an App that fetches data from an API and updates it randomly every 3 seconds. The user has the ability to print the data by clicking a button, which can also be used to stop the random updates. I have managed to implement this fun ...

A tutorial on creating dynamic text animations: sliding text effects on web pages

Does anyone know how to create a sliding in and out effect like the one on this page: ...

Exploring Angular 8 HTTP Observables within the ngOnInit Lifecycle Hook

Currently, I am still a beginner in Angular and learning Angular 8. I am in the process of creating a simple API communication service to retrieve the necessary data for display. Within my main component, there is a sub-component that also needs to fetch ...

Stuffing a container with an image without considering the proportions

I am experimenting with filling a parent <div> with an image without concern for proportions. Despite knowing that it may not look great at all sizes, I just want to test its feasibility. Currently, the image is scaling instead of stretching to fit m ...

How can I use jQuery to retrieve the total number of elements in a dropdown list?

I am working with a dropdown list that looks like this: <select id="ddlProjects"> <option value="315">resproject</option> <option value="320" style-"display:inline">newheavn</option> <option value="395" style="di ...

Challenges Encountered when Making Multiple API Requests

I've encountered a puzzling issue with an ngrx effect I developed to fetch data from multiple API calls. Strangely, while some calls return data successfully, others are returning null for no apparent reason. Effect: @Effect() loadMoveList$: Obse ...

One typical approach in React/JavaScript for monitoring the runtime of every function within a program

Experimenting with different techniques such as performance.now() or new Date().getTime() has been done in order to monitor the processing time of every function/method. However, specifying these methods within each function for time calculation purposes h ...

What could be causing the error I'm encountering while running the 'net' module in Node.js?

I am currently working with .net modular and have opened TCP port 6112. var net = require('net'); var server = net.createServer(function (socket) { //'connection' listener }); server.listen(6112, function () { //'listening ...

Clicking on tabs causes their content to mysteriously vanish

I am working on creating a dynamic menu using jQuery that switches content based on tabs. However, I am facing an issue where clicking on a different <li> item causes the content to disappear. Each list item should correspond to different content sec ...

Experiment with jQuery and JavaScript compatibility specifically on Internet Explorer 6

Seeking advice on the most effective method to test my web app using IE6. I currently have IE8 installed on my computer, and am considering utilizing a Virtual Machine. Are there any other alternatives worth exploring? It is imperative that my jQuery and ...