Advertisement
Guest User

Untitled

a guest
Jan 28th, 2024
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. Modifying the duration of a CSS animation dynamically for each new message directly within HTML is unfortunately not possible. CSS can't directly accept HTML attributes as values. That being said, it can be done using JavaScript or jQuery.
  2.  
  3. Here's an example in which we use JavaScript to read a data attribute from a element and apply it to the inline style:
  4.  
  5. HTML:
  6.  
  7. ```html
  8. <div class='blink' data-blink-speed='1000'>TEST 1</div>
  9. <div class='blink' data-blink-speed='500'>TEST 2</div>
  10. ```
  11.  
  12. JavaScript:
  13.  
  14. ```html
  15. <script>
  16. var blinks = document.querySelectorAll('.blink');
  17. for (var i = 0; i< blinks.length; i++) {
  18. var speed = blinks[i].getAttribute('data-blink-speed');
  19. blinks[i].style.animationDuration = speed + 'ms';
  20. }
  21. </script>
  22. ```
  23.  
  24. In this script, we go through every element with class 'blink', get its 'data-blink-speed' attribute, and use that to set the animation duration.
  25.  
  26. The CSS would remain the same:
  27.  
  28. ```html
  29. <style>
  30. .blink {
  31. animation: blinker linear infinite;
  32. }
  33.  
  34. @keyframes blinker {
  35. 50% {
  36. opacity: 0;
  37. }
  38. }
  39. </style>
  40. ```
  41.  
  42. If you want to use jQuery instead, the code would be:
  43.  
  44. ```html
  45. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  46. <script>
  47. $(document).ready(function() {
  48. $('.blink').each(function() {
  49. var speed = $(this).data('blink-speed');
  50. $(this).css('animation-duration', speed + 'ms');
  51. });
  52. });
  53. </script>
  54. ```
  55.  
  56. This does essentially the same thing as the pure JavaScript example. It goes through all elements with the class 'blink', reads the 'blink-speed' data attribute and applies it as the animation's duration.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement