How can we transfer animation duration and `@keyframe` values through a function in CSS?

In my angular project, I am currently adding animations to text. However, I want to make these animations dynamic.

For instance, I have a CSS class called .slide-in-top with an animation time set to 1.3s. Instead of this static value, I want to be able to set the animation time dynamically from a function like addAnimation(), allowing me to choose between 2, 3 or 4 seconds.

Furthermore, I also wish to customize the values within the keyframes. Currently, the value is set to transform: translateY(-40px), which is static. I intend to modify this value dynamically through the addAnimation() function, making it possible to select values like -30px or -50px.

addAnimation();

function addAnimation(){
 $("#user_text").addClass('slide-in-top');
}
.slide-in-top {
  -webkit-animation: slide-in-top 1.3s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
  animation: slide-in-top 1.3s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}

@-webkit-keyframes slide-in-top {
  0% {
    -webkit-transform: translateY(-40px);
    transform: translateY(-40px);
    opacity: 0;
  }

  100% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes slide-in-top {
  0% {
    -webkit-transform: translateY(-40px);
    transform: translateY(-40px);
    opacity: 0;
  }

  100% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
    opacity: 1;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="margin-top: 20px; background:#0095ff;height:100px;padding:20px">
  <p id="user_text">This is Animated text</p>
</div>

Answer №1

I trust this meets your expectations.

By utilizing the setParameters('1.3s','-50px') method, you are able to dynamically set the animation duration and keyframes values of the transform property.

function incorporateAnimation(animationTitle,animationFormats){

 let styleElement = document.createElement('style');
 styleElement.type='text/css';
 document.head.appendChild(styleElement); 
 let styleElementSheet = styleElement.sheet;
 styleElementSheet.insertRule(`@keyframes ${animationTitle}{
 ${animationFormats} }`,styleElement.length);
 
 styleElementSheet.insertRule(`@-webkit-keyframes ${animationTitle}{
 ${animationFormats} }`,styleElement.length);
}

function applySettings(animDuration,translate){
 $("#user_text").addClass('slide-in-top');
document.getElementsByClassName('slide-in-top')[0].style.animation = `slide-in-top ${animDuration} cubic-bezier(0.250, 0.460, 0.450, 0.940) both`;


incorporateAnimation('slide-in-top', `
  0% {
    -webkit-transform: translateY(${translate});
    transform: translateY(${translate});
    opacity: 0;
  }
  100% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
    opacity: 1;
  }
`);
}
applySettings('1.3s','-50px'); //adjust as needed
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="margin-top: 20px; background:#0095ff;height:100px;padding:20px">
  <p id="user_text">This is Animated text</p>
</div>

Answer №2

If you want to create a cool animation, follow this code snippet

function createAnimation(start, end){
  $( "#user_text" ).css('margin-top', start);
  $( "#user_text" ).css('opacity', '0');
  $( "#user_text" ).animate({
      "margin-top": end,
      "opacity": 1
    }, 1500 );
}

createAnimation("-30px", "0px");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="margin-top: 20px; background:#0095ff;height:100px;padding:20px">
  <p id="user_text">This is Animated text</p>
</div>

Answer №3

If you're looking to avoid potential scaling issues in the future, it's best to steer clear of mixing JQuery and Angular. Instead, consider utilizing Angular animations for a smoother experience. You can easily pass dynamic values using interpolation binding.

Here's a suggestion:

Check out the snippet below for an example of how to implement animation in your project:

import { Component, Input } from '@angular/core';
import { state, trigger, style, animate, transition, keyframes } from '@angular/animations';

@Component({
  selector: 'animate-text',
  template: `
  <div style="margin-bottom: 20px; background:#0095ff;height:100px;padding:20px">
    <p *ngIf="show" [@keyframes]="{value: '', params: {duration: duration, translateStart: translateStart}}">This is Animated text</p>
  </div>
  `,
  animations: [
    trigger('keyframes',[
      transition('void => *', [
        animate('{{ duration }} cubic-bezier(0.250, 0.460, 0.450, 0.940)', keyframes([ 
          style({opacity: 0, transform: 'translateY({{ translateStart }})'}), 
          style({opacity: 1, transform: 'translateY(0px)'})
        ])),
      ])      
    ])
  ]
})
export class AnimateText {
  @Input() duration: string = '1.3s';
  @Input() translateStart: string = '-40px';
  show: boolean = true;

  onMouseUp() {
    this.show = !this.show;
  }
}

For more details on implementation, you can refer to the following code snippet:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  Default (duration: 1.3s, translateY: -40px):
  <animate-text></animate-text>

  duration: 3s, translateY: -30px:
  <animate-text duration='3s' translateStart='-30px'></animate-text>

  duration: 10s, translateY: 80px:
  <animate-text duration='10s' translateStart='80px'></animate-text>
  `
})
export class AppComponent {
}

The above animate-text.component.ts allows for two inputs, namely duration and translateStart. These inputs serve as the dynamic values for the animation duration and translateY value at keyframe 1.

Through the use of interpolation in the animation definition, the values are seamlessly integrated into the animation properties such as params property of the value bound to the animation property

[@keyframes]="{value: '', params: {duration: duration, translateStart: translateStart}}"
.

  • duration -
    animate('{{ duration }} cubic-bezier(0.250, 0.460, 0.450, 0.940)
  • translateStart -
    style({opacity: 0, transform: 'translateY({{ translateStart }})'})

To see a live demonstration, visit: Stackblitz

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

AngularJS2 brings a powerful and seamless implementation of indexedDB for efficient

I'm on the hunt for an indexeddb implementation that works seamlessly with Angularjs2. While I stumbled upon this api at https://github.com/gilf/angular2-indexeddb, it appears to be lacking in active development and may not be ready for production use ...

Tips for interfacing with Angular ColorPicker elements using Selenium WebDriver

Is there a way to automate interactions with Angular ColorPicker components using Selenium WebDriver? Since there is no text field input for hex codes, it relies solely on mouse clicks. For reference, you can check out this example: https://www.primeface ...

Inject a new observable into the current Subject

Having an Angular Subject named event$, I want to attach DOM controls as emitters to this observable when screens are loaded. The observable already has subscribers, so I am using a method to merge another observable with it, as shown below (Subscription m ...

Adjust the size of a menu by modifying its width

Hey everyone, I recently joined this website and I'm still learning how to code. My current project involves creating an off-canvas menu, but I've come across a few challenges. Firstly, does anyone know how to adjust the width of the menu when it ...

What is causing the input tag and button tag to appear on separate lines instead of together?

Here is my HTML and CSS code: <!DOCTYPE html> <html> <head> <title>assignment1</title> <meta charset="utf-8"> <meta name = "description" content="assignment"> <meta name = "keywords" content="php, assignm ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

The challenge of website sizing issues with window scaling and the overlooked initial-scale value in HTML

After encountering sizing issues on Windows 10 due to default scaling set at 125%, I attempted to replicate the issue by adjusting the Scale on Ubuntu. My attempt to fix the size by modifying the initial-scale value did not yield any results: document.que ...

Tips for successfully passing an image using props in Vuejs without experiencing the issue of disappearing content when there is no image present

Is there a way to make a component that can function with or without an image? Currently, when the component doesn't have an image, other contents and styles disappear. How can I resolve this issue? App.Vue: <template> <div id="app&qu ...

An error persists in PhpStorm inspection regarding the absence of AppComponent declaration in an Angular module

After creating a new Angular application, I am encountering the issue of getting the error message "X is not declared in any Angular module" on every component, including the automatically generated AppComponent. Despite having the latest version of the An ...

Creating a border indentation for a table row using the <tr> tag

In my database, there is a table that shows the parent-child relationship. Check out this link for more details The HTML structure of the table is as follows: <table> <tr class="parent_row"> <td >1</td> <td>2</t ...

The Google Chrome console is failing to display the accurate line numbers for JavaScript errors

Currently, I find myself grappling with debugging in an angular project built with ionic framework. Utilizing ion-router-outlet, I attempt to troubleshoot using the Google Chrome console. Unfortunately, the console is displaying inaccurate line numbers mak ...

Struggling to transfer array data from service to component

I am currently working on passing an array from service.ts to a component. My goal is to display the array elements in a dialog box. However, I encountered a Typescript error TypeError: Cannot read property 'departmentArr' of undefined. I am str ...

Reducing the size of CSS classes and IDs

I am searching for a way to automatically compress classes and ids in an .html file. This specific file is generated through a sequence of gulp commands. I attempted to use the Munch command line application, but it had adverse effects on the file by elimi ...

adjustable backdrops

Hi there, I'm trying to create a background image that resizes with the window while maintaining its proportions. I want to achieve this using CSS only. I've been searching for a solution but haven't found anything that works for me. I even ...

How can I align a div in a vertical manner if it is displayed as a circle?

This is the creation I have come up with: This is the design I am aiming for: Below is the code I have written: <div id="OR"><span style=" vertical-align: middle;background:blue;">OR</span></div> Here is the corresponding CSS: ...

How come characteristics of one particular div element are transferring to unrelated div elements?

Recently, I created a small practice website and encountered an issue that is quite frustrating. Here's the div structure I used: <div class="work-process"> <div class="container" align="center"> <div class="col- ...

Is there a way to start playing HTML5 Audio without having to wait for the entire buffering process to finish

My internet connection is fast but it still takes 2-3 seconds for the song to start playing. The file size is around 3mb-4mb, with an average bitrate of 128kbps MP3. I've tried setting preload="auto" but it didn't improve much. Is there a way to ...

Passing parameters to an Angular 2 component

When it comes to passing a string parameter to my component, I need the flexibility to adjust the parameters of services based on the passed value. Here's how I handle it: In my index.html, I simply call my component and pass the required parameter. ...

What is the best way to center align my button using CSS?

I'm struggling with aligning this button in CSS to the center: .btn { background-color: #44c767; -moz-border-radius: 28px; -webkit-border-radius: 28px; border-radius: 28px; border: 1px solid #18ab29; display: inline-block; cursor: poi ...

Using JavaScript, HTML, and CSS to select slices of a donut pie chart created with SVG

I have successfully implemented CSS hover effects and can manipulate the HTML to use the .active class. However, I am facing difficulties in making my pie slices switch to the active state upon click. Moreover, once this is resolved, I aim to enable select ...