What is the most effective method for incorporating keyframes using JavaScript in a dynamic way?

Is there a way to animate an HTML element by using a variable with keyframes, but without directly manipulating the DOM?

Below is the HTML code:

<div class="pawn" id="pawn1"></div>

Here is the CSS keyframes code:

@keyframes mov_pawn_up {
    0% {
        bottom: 0%;
    }
    100% {
        bottom: 700%;
    }
}

I am looking for a solution that allows me to customize the bottom property using a variable.

Any advice or suggestions would be greatly appreciated. Thank you!

Answer №1

To achieve this effect, CSS variables can be used. Here is a simplified version of the concept:

const board = document.querySelector(".board");
const root = document.documentElement;

const movePiece = (evt, y) => {
  const piece = evt.target;
  piece.classList.remove("active");
  piece.style.bottom = y + "px";
};

board.addEventListener("click", evt => {
  const clickedPiece = evt.target.closest(".piece");
  if (!clickedPiece) return;
  const startY = Number(clickedPiece.dataset.y);
  const endY = startY - 20;
  
  root.style.setProperty('--bottom-start', startY + "px");
  root.style.setProperty('--bottom-end', endY + "px");

  clickedPiece.removeEventListener('animationend', movePiece);
  clickedPiece.addEventListener('animationend', evt => movePiece(evt, endY));
  clickedPiece.dataset.y = endY;
  
  clickedPiece.classList.add("active");
});
:root {
  --bottom-start: 0px;
  --bottom-end: -0px;
}

div {
  position: relative;
}

span.piece {
  position: relative;
}

span.piece.active {
  animation-duration: 1.5s;
  animation-name: move_pawn;
}

@keyframes move_pawn {
    0% {
        bottom: var(--bottom-start);
        color: blue;
    }
    100% {
        bottom: var(--bottom-end);
        color: black;
    }
}
<div class="board">
  <span class="piece" data-y="0">X</span>
  <span class="piece" data-y="0">X</span>
  <span class="piece" data-y="0">X</span>
  <span class="piece" data-y="0">X</span>
</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

I'm curious about the method used to create this body fadeIn effect

Recently, I stumbled upon the website "". I must say, it is truly remarkable. I can't help but wonder how the content on this page is cleverly faded in and slides up. This specific page caught my attention: ...

React Table in Modal Using Custom Hook State

I'm facing some difficulties with the React useState hook. Currently, I have a modal that pops up after submitting a form. Before loading the modal, the application calls an API to fetch data, which is then displayed in a table within the modal. The ...

Enhancing compatibility between Symfony 2.3 and 1.4 for seamless user experience

Recently, I encountered a situation at work where we have two different websites that share the same user login credentials. One website is built on Symfony 2.3 while the other one relies on version 1.4. My boss has assigned me the task of enabling seamles ...

Error in Mongodb: Unable to convert value into ObjectId

Currently, I am attempting to retrieve only the posts belonging to users using the following code snippet: router.get("/:username", async (req, res) => { try { const user = await User.findOne({ username: req.params.username }); const ...

Prevent touch swiping on Bootstrap carousel in Safari

After adding the code snippet below to my Bootstrap carousel, I've encountered an issue where I am unable to disable touch swiping on iOS devices for the carousel. <div id="infinityWarContentWrapper" class="carousel slide carousel-sy ...

What is the best way to position a div in relation to a table header (th) but not inside it?

I'm trying to create a table header that displays a help text (div) when clicked on. However, the help div is causing the table header to be larger than the other headers. Below is the code snippet: #help_box { border-radius: 20px; ba ...

Having trouble aligning two divs horizontally on the same line in Bootstrap 4

I am facing an issue with my HTML code where I have two div elements that are supposed to be horizontally aligned, but the second div is appearing underneath the first one. To fix this, I tried using bootstrap classes for alignment. <div class="c ...

Error: The global variable cannot be emptied due to an issue with the Ajax request

As someone who is relatively new to the world of Javascript/jquery and async, I have spent a significant amount of time reading through various forums. Unfortunately, I have yet to come across a solution that addresses my specific issue. The problem at ha ...

How is it that my initial response appears correct in the first log, but then suddenly changes to a 1?

I've encountered a strange issue where the response appears correctly in the initial log, but later changes to a '1' when console.log(data); is called. The screenshot illustrates the pattern: https://i.sstatic.net/zaXcg.png If you expand ...

What could be causing my Angular code to submit back unexpectedly?

My goal is to make an initial call to the database to populate some dropdowns, after which all actions are done through AJAX. However, whenever I click a button on the page, it seems to be posting back and calling the function that fetches dropdown values ...

Utilizing a custom function declared within the component to handle changes in Angular's ngOnChanges

Although it may seem like a simple question, I'm struggling to find a solution. Here's the issue at hand: In my Angular Component, there's a function that I need help with. export class RolesListComponent implements OnInit, OnChanges { ...

Having trouble getting JavaScript to work when returned via AJAX

After triggering a lightbox by clicking on a business name, I encountered an issue when trying to replicate the same functionality using AJAX. The lightbox fails to show up. Can anyone provide assistance? The following code represents a 3rd party publishe ...

Text-color in the v-tooltip

Is there a way to change the text color of v-tooltips components without affecting the tooltip background color? I attempted to inspect the element, but the tooltip only appears on hover, making it impossible to inspect. Below is the code snippet: < ...

Explore within another map and analyze the node to spot the differences

I have some questions about iterating through a JavaScript Object and using array functions in JavaScript. Let's assume I have the following variables: var json1 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]"; var json2 = "[{"id": 1, "name":"x"}, ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

Assistance needed with WebSocket and Node.js: Unable to connect to wss://domain:8080 - Issue is not specific to any browser

Greetings, this is my initial inquiry on stack overflow so I'll give it my best shot. Despite going through numerous related questions, I haven't found the solution to my issue. I recently delved into Node.js because I required websockets for ce ...

Exploring Firebase database with AngularJS to iterate through an array of objects

I'm working on an app that pulls data from a Firebase database, but I'm running into an issue. When I try to loop through the data and display it on the page, nothing shows up. However, if I use console.log to output the data, it's all there ...

Issue with the page base and Jquery Ui tabs URL

Having an issue with jqueryui tabs. Here's the code I'm using: // jQuery Tabs $( "#tabs" ).tabs(); // Open correct tab based on URL hash var hash = window.location.hash; var index = $("#tabs a").index($('#link-'+hash.replace('#& ...

"Typescript throws a mysterious 'Undefined value' error post-assignment

I'm currently working on a task to fetch my customer's branding information based on their Id using Angular. First, I retrieve all the customer data: this.subscription = this.burstService.getBurst().subscribe(async(response) => { if (r ...

How to vertically align and center multiple divs with Flexbox programming

I have been grappling with the challenge of aligning two sets of rows vertically, each consisting of an image on one side and text on the other. While I usually use flex to achieve vertical alignment, it seems that a different approach is needed in this pa ...