Incorporating variables into CSS animations

div {
  animation-duration: 3s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-right: 100%;
    height: 300%; 
  }

  to {
    margin-right: 0%;
    height: 100%;
  }
}

Is it possible to dynamically pass the values of margin-right and height parameters from Javascript to the above animation CSS code?

Answer №1

By utilizing CSS variables, achieving this effect is straightforward:

document.querySelector('.element1').style.setProperty('--m','100%');
document.querySelector('.element1').style.setProperty('--w','300%');
.element1, .element2 {
  animation-duration: 3s;
  animation-name: sliding;
}

@keyframes sliding {
  from {
    margin-left: var(--m, 0%);
    width: var(--w, 100%);
  }
  to {
    margin-left: 0%;
    width: 100%;
  }
}
<p class="element1">
 This paragraph will not animate as the animation will use the default value assigned to the CSS variable
</p>
<p class="element2">
  This paragraph will animate because the CSS variable was modified using JavaScript
</p>

Answer №2

One alternative method to achieve this could be utilizing: Element.animate()

var m = "100%";
var w = "300%";

document.getElementsByClassName('p2')[0].animate([{
        marginLeft: m,
        width: w
    },
    {
        marginLeft: '0%',
        width: '100%'
    }
], {
    duration: 2000,
});
<!DOCTYPE html>
<html>
<head>
<style>

</style>
</head>
<body>
<p class="p1">
 This will not animate as the animation will use the default value set to the variable
</p>
<p class="p2">
  This will animate because we changed the CSS variable using JS
</p>
</body>
</html>

Answer №3

Temani Afif's response, However, one animation has been removed for better clarity on the process.

By utilizing CSS variables, achieving this effect is made simple:

document.querySelector('.p2').style.setProperty('--m','100%');
   
.p1,.p2 {
  animation-duration: 3s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-left: var(--m, 0%);
   
  }
  to {
    margin-left: 0%;
    
  }
}
<p class="p1">
 This won't animate as the animation will use the default value assigned to the variable
</p>
<p class="p2">
  This, on the other hand, will animate since we modified the CSS variable through JavaScript
</p>

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

What are the methods to ascertain whether an HTML element possesses a pseudo element?

Is there a method to identify whether an HTML element has a pseudo element (::before / ::after) applied to it without invoking the function: window.getComputedStyle(element, ":before/:after"); MODIFIED: the response is NEGATIVE The issue with getCompute ...

Create a full bottom shadow for a circular shape using CSS 3

Hey there, I'm having an issue with creating a separation effect for a circle. I've been using the box-shadow property like this: box-shadow: 0 1px 0 rgba(0,0,0,.2);. However, as you can see in the image, the shadow on the left and right sides is ...

In Firefox, the CSS height and width values are displayed as X pixels, whereas in Internet Explorer, they are automatically set to 'auto'

When it comes to measuring div box dimensions, jQuery can be a handy tool. Here is an example code snippet: $(document).ready(function(){ var h = $("#testbox").css("height"); }); Interestingly, the same code can give different results in different brow ...

Ways to eliminate spacing around lists?

I am trying to remove the margin on the left side of a list that contains 3 items. Here is my code: ul li { display: inline; list-style: none; } <ul> <li>I have margin space on my left side</li> <li>List 2</li> & ...

Is it true that Internet Explorer does not support border radius?

Styling with CSS border-bottom: 1px solid silver; background-color: #000; background: rgb(51,51,51); /* Old browsers */ background: -moz-linear-gradient(top, rgba(51,51,51,1) 0%, rgba(153,153,153,1) 100%); /* FF3.6+ */ background: -webkit-gradient(linear, ...

Modify CSS image according to the user interface language in asp.net

Is there a way to dynamically change the image based on different cultures in my ASP.NET webpage? I have successfully been able to switch strings using a resource file, but I am unsure how to handle images. Currently, I have an A tag with a specific clas ...

What is the best way to center the input on the page?

Does anyone know how to align the <input type="text"> in the center? I'm trying to create a login form but having trouble with positioning the input element. ...

Eliminated the right margin for desktop display

I'm looking to have a menu on the right side of my page. It looks good on mobile view with the menu aligned to the left and white space on the right. However, on desktop view, I want the menu to be aligned to the right with white space on the left. Ho ...

Steps for adjusting an image in a Bootstrap Carousel

Currently tackling a simple bootstrap Carousel for a school project. I've adjusted the max-height of the images to 400px but it seems like only the top part of the images is visible. I attempted to adjust the margins on the image, and even thought abo ...

Personalized modify and remove elements on a row of the DataGrid material-ui version 5 component when hovered over

In my React Js app, I am utilizing Material UI components or MUI v5 as the UI library for my project. Within the DataGrid/DataGridPro component, I am implementing a custom edit and delete row feature. The requirement is to display edit and delete icons w ...

Having trouble with images not showing up on React applications built with webpack?

Hey there! I decided not to use the create react app command and instead built everything from scratch. Below is my webpack configuration: const path = require("path"); module.exports = { mode: "development", entry: "./index.js", output: { pa ...

Assistance needed in restructuring code to eliminate white space between Divs

I am looking to combine two divs in the header section of my website. Both divs should have a black background with no white space between them. Can anyone provide advice on this? Additionally, I would appreciate any recommendations on how to structure my ...

browsersync fails to refresh when alterations are made in the .css files

Why is browsersync not injecting the css correctly? Here is my code: const gulp = require('gulp'), sass = require('gulp-sass'), autoprefixer = require('gulp-autoprefixer'), browserSync = require('browser-sync ...

The Bootstrap Input-Group with Spinner displays an unusual spinning shape that resembles the letter D

I am encountering an issue with a unique form that sends each line of input as a separate request upon submission. I am looking to add a spinner at the end of each line, but I am facing a problem where instead of a circular spinner, I am getting a spinning ...

Move the scroll bar away from the scrollable div and reposition it on a different part of the page using CSS

Is it possible to use CSS to position the scrollbar of a div that takes up the left half of my page with overflow-y: scroll to be where the page scrollbar would normally be (far right side of the page)? I've experimented with the ::-webkit-scrollbar ...

Is there a specific CSS selector that targets elements with "multiline" content?

My website has a menu that displays with the following CSS: a { background:red; } <a href="#">Home</a> <a href="#">Downloads</a> <a href="#">Contact</a> <a href="#">FAQ</a> <a href="#">Disclaimer&l ...

What is the method for updating the value of the Sass variable in Angular 4?

Within the file app.component.scss, there is a variable named $color that has been set to 'red'. What steps can be taken within the file app.component.ts in order to access this variable and change its value to 'green'? ...

How to apply background images to LI elements using CSS

I've been experimenting with CSS-generated tabs to display an active state of an arrow underneath the tab. I tried using the background position properties to position the image for the hover event, but it would extend beyond the predefined boundaries ...

What could be causing my fixed element to disappear when the webpage is not long enough?

OBJECTIVE: a div is { position:fixed; bottom:0% } it has a genuine height and width; the z-index is the highest in the document = so, it should always be visible! ISSUE: mobile browsers 'cut' the bottom end of the page when zooming out. ...

Expanding Bootstrap 5 navbar-nav to occupy entire screen space in collapsed state

Hello everyone, I hope you are doing well! I am currently working on a website project using Bootstrap 5 and have encountered an issue with the navbar toggler. While the toggler is functioning properly, I am having trouble making it fill the full width o ...