What is the best way to initiate a new animation from the current position?

Here is my custom box:

<div class="customBox"></div>

It features a unique animation:

.customBox{
  animation:right 5s;
  animation-fill-mode:forwards;
  padding:50px;
  width:0px;
  height:0px;
  display:block;
  background-color:black;
}
@keyframes 

right{from{left:0px;}to{left:300px 
;}}
@keyframes 
left{from{right:0px;}to{right:300p 
x;}}

I also have two buttons:

<button onclick="leftFunction">left</button>
<button onclick="rightFunction">right</button>

If I click left, the box will move to the left. However, if I click right while it's moving left, I want the left animation to stop and the right animation to start from the current position without teleporting.

I'm seeking assistance on this issue. I'm new to coding resources like Stack Overflow.

Below is the JavaScript code:

function leftFunction() {
             
document.getElementById("myDIV").style.animation 
= "left 4s";
}
function rightFunction() {
              
 document.getElementById("myDIV").style. 
animation = "right 4s";
}

Answer №1

After reviewing the code you provided, I noticed a few issues that needed to be addressed, but overall you were headed in the right direction.

  1. The DOM method was targeting an element with an ID of myDIV, which did not exist. I modified it to document.querySelector(".mybox") as that is the class name of your div.

  2. You forgot to call the function on your onclick handler, which may have caused the functionality to not work properly. Remember to add parentheses () to invoke it on click.

  3. The code layout lacked proper spacing conventions, possibly due to constraints when posting on Stack Overflow. However, I made necessary adjustments for better readability.

  4. Position values were being set without declaring a position property. I set it to relative to ensure the div stays in the document flow.

  5. Changing both left and right properties separately could lead to unexpected resizing. I changed it to only affect the left property for consistency.

Here is the solution:

Modify your keyframes to update only the left property. Call the function from onclick and pass the event object for seamless animation changes based on target elements.

Utilize CSS custom properties to allow JavaScript to manipulate values effectively. Start the animations from the custom property --cur-pos.

When the function is triggered, fetch the computed left value of the div using getComputedStyle(), and update the custom property --cur-pos accordingly. This ensures the animation starts from the current position of the div.

By following these steps, you should be all set. Adjust the starting --cur-pos value and the end to values as needed, ensuring to update either the left or right positions for horizontal movement, not both simultaneously.

function changeAnimation(e) {
  const box = document.querySelector(".mybox")
  const pos = window.getComputedStyle(box).left
  box.style.setProperty("--cur-pos", pos)
  box.style.animationName = e.target.innerHTML
}
.mybox {
  --cur-pos: 150px;
  width: 100px;
  height: 100px;
  background-color: black;
  position: relative;
  animation: right 4s forwards;
}

@keyframes right {
  from { left: var(--cur-pos); }
  to { left: 300px; }
}

@keyframes left {
  from { left: var(--cur-pos); }
  to { left: 0px; }
}
<div class="mybox"></div>
<button onclick="changeAnimation(event)">left</button>
<button onclick="changeAnimation(event)">right</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

Is it recommended to use separate Controllers for each tab in Angular JS to load the pane?

Recently delving into the world of Angular JS and eagerly seeking expert advice and suggestions. Would it be advisable to use separate controllers for initializing each Tab to load the Pane content? Is assigning separate controllers a recommended approac ...

Tips for transmitting information from the main window to a child in JavaScript

Being relatively new to JavaScript, I am attempting to transfer a value entered into an input text field on a parent window to its child window when a button on the parent window is clicked. The parent window features an input field for entering a number a ...

Modifying button text with jQuery is not feasible

I'm facing a challenge with jQuery and I need the help of experienced wizards. I have a Squarespace page here: . However, changing the innerHTML of a button using jQuery seems to be escaping my grasp. My goal is to change the text in the "Add to car ...

What is the best way to incorporate several php files into a WordPress post?

I have developed a system that retrieves information from a database and presents it in multiple text files. Now, I am looking to move this system to a page on a WordPress website. I have already created a custom page named page-slug.php and added the ne ...

Tips on making Material-UI Drawer compress other content when it is open

Seeking assistance from those familiar with CSS and Material UI! I'm currently working on implementing a Material UI Drawer component that doesn't just slide out over the top of the page content, but actually causes the page content to adjust aro ...

Using the Context API dispatch (consumer) within the _app.js class component in Next.js

How can I access the dispatch Context API methods in the _app.js file? The issue I am facing is that I am using React hooks along with Context API, and as _app.js is a Class component, I cannot directly use hooks within it. Below is my current code snipp ...

An Exploration into the Error Situations of NPM Request Library

I'm encountering an issue with the callback in my request function. I'm trying to figure out the specific circumstances under which an error is passed to this callback. const req = require('request'); req('http://www.google.com&ap ...

Ways to avoid losing data when a page is refreshed

After encountering a frustrating issue with my form, I turned to research in hopes of finding a solution. However, each attempt has resulted in disappointment as the data is lost every time the page is refreshed. If anyone has advice on how to prevent th ...

"Failed authentication for client" in the testing environment of PayPal sandbox

I obtained the code from github and updated the Client ID & App Secret accordingly. It worked flawlessly. https://github.com/paypal-examples/docs-examples/tree/main/advanced-integration However, upon integrating the codes into my project, I encountered th ...

Enhancing my code by implementing various conditions in React

Looking for ways to enhance my code quality (Very Important, Important, Medium, Low, Good, Excellent,...) : { Header: "Opinion", accessor: (row) => row.opinion, Cell: props => <span> {props.value == ...

Combine the information from 3 separate subscriptions into a single object using RxJS in Angular 9

I am seeking assistance with merging data from 3 different sensors into one object. I am using Cordova plugins to retrieve accelerometer, gyroscope, and magnetometer data. However, I am facing an issue in subscribing to all three observables simultaneously ...

What could be causing Media-Query to fail when using the max-width media feature?

I recently added a max-width media feature to my code, but for some reason, the colors aren't changing when the width is less than 300px. I've been trying to inspect elements on my laptop to troubleshoot the issue. Additionally, I've made su ...

Refresh numerous HTML <div>'s using data from a JSON object

Looking to automatically update the homepage of my website with the ten most recent "posts" from the server. Here's an example HTML format: <div id="post1"> <p id="link"> </p> </div> <div id="post2"> <p id="li ...

Discovering the initial vacant row within an HTML table with Javascript

Below is a snippet of code that generates a table with 6 rows. The last two rows remain empty. The JavaScript logic in the code correctly determines and displays the total number of rows in the table. I'm currently looking for a way to identify the ...

Issue with Slider Width in WP 5.6 editor and ACF Pro causing layout problems

Is anyone else experiencing a specific issue after updating to WP 5.6? Since the update, all my websites are facing problems with rendering a Slick Slider in the Block Editor. Interestingly, everything looks fine on the front-end. The root of the problem ...

Navigating with Express and Vue

Currently, I am working on a basic web page that has an index '/' and a 404 page to handle errors at '/404'. In my express app setup, I have the following configuration: // Entry Point app.use("/", express.static(resolve(__di ...

GTM - monitoring the most recent clicked element's input data

Custom Script function() { var inputs = document.getElementsByTagName("input"), selectedRadios = []; for (var i = 0;i < inputs.length;i++) { if(inputs[i].type==="checkbox" && inputs[i].checked) { selectedRadios.push(inputs[i].value); ...

Implementing a backdrop while content is floating

I am facing an issue with a div that has 2 columns. The height of the left column is dynamically changing, whereas the right column always remains fixed in height. To achieve this, I have used the float property for both column divs within the container di ...

Is there a way to utilize PHP/HTML to exhibit a diverse array of random images as dynamic background visuals?

I'm currently learning the process of constructing a website. I've successfully constructed the index page, and below you will find the PHP and HTML code: <?php session_start(); $pngFiles = array('image1.png', 'image2.jpeg' ...

Issues with playing Html 5 video arise when making an ajax call

My goal is to implement an AJAX call followed by displaying an HTML5 video. The provided code snippet seems to be ineffective. $.ajax({ type: "POST", url: "Videos.aspx/GetBlocs", contentType: "application/json; charse ...