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

Utilizing ReactJS useState to eliminate a className

Basically, I'm trying to remove a className from an element when a button is clicked. I've attempted to use useState hooks and a regular function, with the onClick event on the button triggering this function/setUseState. However, the className l ...

A tip for transferring the value of a binding variable to a method within the template when the button is clicked

I am currently exploring the concept of binding between parent and child components using @Input, @Output, and EventEmitter decorators. This is demonstrated in the HTML snippet below: <h1 appItemDetails [item]="currentItem">{{currentItem}}& ...

Ways to retrieve the checkbox value using PHP in conjunction with XML

I am currently in the process of learning PHP, XML, AJAX, and other related technologies. I have a form that is working fine for the most part, but I am facing an issue with passing the value/state of a checkbox to my PHP script. It's worth mentionin ...

Changing the custom route in React Router to utilize a render prop instead of the component prop

I'm currently working on a React app that incorporates React Router. I've been encountering a bug in my code stemming from my custom ProtectedRoute component: const ProtectedRoute = ({ component, ...args }) => ( <Route component={with ...

Utilizing inputRef in conjunction with MUI's useAutocomplete

Is there a way to pass the "inputRef" to Material UI's useAutocomplete? I'm looking to set a custom reference on the input, but the getInputProps() method from useAutocomplete already requires its own reference. I've attempted various appr ...

Retrieving the value of the button with $(this).val() is the only function that newusername performs

My issue arises when trying to send my data to a PHP file; it only sends the value of the <button> or <input type="button">. If I remove the variable definitions, it will only send the data as a string if they are formatted like this: newuser ...

Cannot get Firebase's set() method to work when called within onAuthStateChanged() function

As I embark on developing my first significant web application using ReactJS with Firebase as the backend database, everything was progressing smoothly until a troublesome issue surfaced. The hurdle I encountered involves saving user information upon thei ...

Saving similar and dissimilar information in a database

I have been working on implementing a Like and Unlike feature for users to interact with products. Following this tutorial at , I've completed the necessary steps. However, I'm facing an issue where the likes are not being stored in the database ...

Save a newly uploaded image to Github utilizing NodeJS and the Github API

Struggling to upload an image to my Github repo using NodeJS and Github API has been a challenge for me. I have managed to create the SHA, Commit Tree, and all necessary steps, but the final hurdle is passing the image to the API and saving it as an actual ...

What could be the reason for Chrome breaking up this straightforward bootstrap header into two lines?

Why is it that the code below displays correctly in one line in both FF and IE, but Chrome for some reason is showing it on two lines as if both span and button elements had "display:block;"? Even though the button has a computed display of "inline-block," ...

Storing dropdown selection in database using Laravel form and AJAX

In my controller (FocalController.php), I have generated a dropdown list using the following code: $focalData = DB::table('role_users')->orderBy('users.id','DESC') ->leftJoin('users', function($j ...

Leverage jquery to adjust the height or width of an element depending on which dimension is larger

I'm a beginner in jquery and html and am currently developing a gallery webpage. The functionality involves setting the selected image as the page background and then scrolling vertically based on the mouse pointer's position. This works well for ...

Guide for executing Gulp tasks in a sequence one by one

Here is an example snippet: gulp.task "coffee", -> gulp.src("src/server/**/*.coffee") .pipe(coffee {bare: true}).on("error",gutil.log) .pipe(gulp.dest "bin") gulp.task "clean",-> gulp.src("bin", {read:false}) .pipe c ...

Sending a unicode PHP variable to JavaScript is a breeze

I am attempting to transfer the titles and excerpts of Persian Wordpress posts to JavaScript. Below is the code in a .php script file: function change(){ document.getElementById("link").innerHTML = '<a href="$links[2]">$titles[2]< ...

Tips for maintaining the data on a page continuously updating in AngularJS

I have this code snippet: $cookieStore.put('profileData', $scope.profileData); var profileData = $cookieStore.get('profileData'); $scope.init = function(){ var profileData = $cookieStore.get('pr ...

Accessing HP ALM with REST and JavaScript on a local server: A step-by-step guide

I am trying to access ALM using locally written JavaScript in the browser (IE11, Firefox) through the REST API, but I am unable to login. Below is the code snippet where I am attempting to request the LWSSO cookie with jQuery: var auth = btoa(USER+":"+PAS ...

Request Fancybox from parent document within an iframe

I have two pages, my index.html and social.html. I recently cleaned up my index.html file and left only the necessary jQuery code for using fancybox. My goal is to display images from social.html within fancybox when clicked on, but it should open in index ...

What is the best way to implement a recursive service call that is triggered automatically at regular intervals?

I came across this code snippet: us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); $interval(function () { us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); }, ...

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...

Adjusting hyperlinks placement based on window size changes using jQuery

On resizing the screen, I am moving the sub-nav links to the '#MoreList' It works well initially, but when the window is expanded again, the links remain in the #MoreList instead of going back to their original positions if there is enough space ...