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

Words appear on the screen, flowing smoothly from left to right

I am trying to create a hover effect where a caption appears when an image is hovered over. The text should slide in from left to right, causing the container to grow along the X axis as the image is hovered over. I have managed to make the text appear on ...

Looking for assistance with arranging and managing several containers, buttons, and modals?

My goal is to create a grid of photos that, when hovered over, display a button that can be clicked to open a modal. I initially got one photo to work with this functionality, but as I added more photos and buttons, I encountered an issue where the first b ...

Bootstrap 4 Navigation Bar: Aligning dropdown menu to the right with overflow opening on the right side

Utilizing Bootstrap 4 for a simple navbar, I recently noticed that my right-aligned dropdown opens to the right, causing overflow and displaying the horizontal browser scrollbar. Here is the code for the navbar: <nav class="navbar navbar-expand-lg nav ...

Is there a way to optimize downloading multiple identical images using html, css, jquery, etc.?

My chess board features 64 squares, each with a picture of a board piece on either a light or dark square. To ensure proper formatting, a Clear knight is placed on the board. The design utilizes a div element with a background image (representing light or ...

Tips for transferring a jQuery array to PHP

I am encountering an issue when trying to send a jQuery array to PHP. Initially, I have one form in HTML and upon clicking 'add', I end up with two forms. Afterwards, I input data into the form which is then stored in a jQuery array. However, I a ...

Roll out a custom-built server for an Angular 7, MongoDB, Express, and Node application

I am seeking to host my Angular application with Node.js, MongoDB, and Express.js on a server of my own. My current deployment method involves: -> ng build --prod (generates output in the dist folder) -> ng serve from the dist directory To start th ...

When utilizing <number | null> or <number | undefined> within computed() or signals(), it may not function properly if the value is 0

I've encountered an issue while implementing signals and computed in my new Angular project. There's a computed value that holds an id, which is initially not set and will be assigned by user interaction. To handle this initial state, I attempte ...

Transforming a JSON string containing multiple arrays into a JavaScript object

My JSON file is structured as follows: { "items":[ { "username":"abc", "orderID":"1234", "commentHistory":[ { "comment":"Comment Date: 2016/12/09 13:44:23" }, { ...

The variable 'cache' is not recognized by Angular

Everything runs smoothly on my local Angular app, but once deployed on Heroku using a Go server, I encounter issues with aot being disabled in the Angular build on Chrome and Opera, particularly on mobile devices using Linux and OSX. However, Safari presen ...

When a file is modified in Angular, it triggers an error prompting the need to restart the 'npm' service

Whenever I make changes to a file in my Angular application, I encounter the following error: ERROR in ./src/app/@theme/components/auth/index.js Module build failed: Error: ENOENT: no such file or directory, open 'C:\Dev\Ng\ngx-a ...

Press the html button and activate the button using Visual Basic

Being new to Visual Basic, I have created a simple app using the WebBrowser component. The web page that loads contains an HTML button. I want this HTML button press to enable a button in Visual Basic, but I don't know how to do it. I have researched ...

The continuity of service value across parent and child components is not guaranteed

My goal is to update a value in a service from one component and retrieve it in another. The structure of my components is as follows: parent => child => grandchild When I modify the service value in the first child component, the parent receives t ...

Tips for creating a scrollable modal with a form embedded within

Is there a way to enable scrolling in a modal that contains a form? <div class="modal fade" id="assignModal" data-coreui-backdrop="static" data-coreui-keyboard="false" aria-labelledby="staticBackdropLabel&q ...

When the parent element is centered, align the children to the left

Can children be aligned to the left when the parent is aligned to the center? I have a list of elements where the parent block should be centered, but the children need to align to the left. Now I found a solution to align the children to the center as w ...

The lower border is unresponsive in the CSS/HTML code currently in use

Currently diving into the world of Web Development, I find myself tackling the CSS part. My latest challenge involves adding a bottom border to an element, but no matter what I try, the border just won't show up. I've scoured resources for soluti ...

Tips for saving information from a textarea into an HTML file

I have a unique question regarding the usage of $fopen and $fwrite functions. My goal is to include a button named "save as HTML" below a textarea. Upon clicking this button, I want a popup box to appear mimicking the 'save as...' dialog window ...

"Facing a dilemma with Javascript's Facebox getElementById function - not fetching any

Utilizing facebox, I am initiating a small modal dialog with a form and attempting to retrieve the value from a text field on that form using javascript. Below is the HTML code: <div id="dialog-form95" style="display:none"> <div class="block"> ...

Error found in the HTML tag data when viewing the page source for an issue

I am displaying some data from my express to ejs in HTML tag format. It appears correctly on the ejs template page and the web page. However, when I check the page source, the HTML tags are encoded and displayed as unescaped characters. Is there a solution ...

Troubleshooting z-index problem with background image and parent tag of image

I seem to be facing an issue with the z-index property. Here is the code snippet in question: <div id="sidebarCont"> <div id="avatarCont" class="mask"> <img id="" class="" src="img.jpg" alt=""/> </div> And here is the correspo ...

How can I add text to the title of a border using Bootstrap5?

I am attempting to create a design where text appears within the border of an element. I am currently utilizing Bootstrap 5 and jQuery for this project. Despite my efforts with fieldset and legend elements, I have not been successful in achieving the desir ...