Retrieve the status of a CSS animation using JavaScript and display it within an element or log it to the console for future modifications

I am experimenting with CSS3 animations to create a marquee effect and want to trigger a function when the animation changes from running to paused or initial state.

HTML:

<div class='animationBackground'><p id="marqueeText">Scrolling Text Goes Here</p></div>
<div id="animationState">Animation State</div>
<button id='stop' type"button" onclick=stopInterval()>Stop Logging</button>

CSS:

@keyframes marquee
    {
        0%   { transform: translate(0%, 0); }
        100% { transform: translate(-200%, 0);}
    }

    p {
        margin-left: 100%;
        padding-inline-end: 50px;
        display: inline-block;
        white-space: nowrap;
        color: #ffffff;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        font-size: 30pt;
        z-index: 10;
        animation: marquee 25s linear 0s 1
    }

    .animation{
        width: 100%;
        background-color: darkblue;
        vertical-align: bottom;
    }

JavaScript:

var myVar = setInterval(myTimer, 5000);

function myTimer() {
    var marqueeText = document.getElementById('marqueeText');
    var animationState = document.getElementById('animationState');
    animationState.innerHTML = marqueeText.style.animationPlayState;
    console.log(marqueeText.style.animationPlayState);

    if(marqueeText.style.animationPlayState == "running"){
        doSomething();
    }

}

function stopInterval(){
    clearInterval(myVar);
}

The following code does not display any output:

animationState.innerHTML = animatedText.style.animationPlayState;

Similarly, this code results in a blank <div> and no output in the console:

console.log(animatedText.style.animationPlayState);

Is it feasible to obtain and manipulate states like running|paused|initial|inherit using Javascript through the doSomething() function?

Answer №1

It's quite peculiar, not sure if it's a glitch in the browser or something else.. but it appears that accessing that specific property of the element is not feasible, even when explicitly defined in the CSS.

getComputedStyle seems to be effective though.

var myVar = setInterval(myTimer, 2000);

var marqueeText = document.getElementById('marqueeText');
function myTimer() {
    var computedStyle = window.getComputedStyle(marqueeText);
    printState(computedStyle.animationPlayState);
    if(computedStyle.animationPlayState == "running"){
        //doSomething();
    }

}

function stopInterval(){
    clearInterval(myVar);
    marqueeText.style.animationPlayState = "paused";
    var computedStyle = window.getComputedStyle(marqueeText)
    printState(computedStyle.animationPlayState);
}

function printState(state){
  var animationState = document.getElementById('animationState');
  console.log(state);
  animationState.innerHTML = state;
}
@keyframes marquee
    {
        0%   { transform: translate(0%, 0); }
        100% { transform: translate(-200%, 0);}
    }

    p {
      color:#000;
        margin-left: 100%;
        padding-inline-end: 50px;
        display: inline-block;
        white-space: nowrap;
        
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        font-size: 30pt;
        z-index: 10;
        animation: marquee 25s linear 0s 1;
        
    }

    .animation{
        width: 100%;
        background-color: darkblue;
        vertical-align: bottom;
    }
<div class='animationBackground'><p id="marqueeText">Scrolling Text Goes Here</p></div>
<div id="animationState">Animation State</div>
<button id='stop' type"button" onclick=stopInterval()>Stop Logging</button>

Add witty remark about the deprecation of marquee for a reason here :-p

Answer №2

If you're looking to create animations based on keyframes and want to check their status programmatically, consider utilizing the Web Animation API. You can use a callback function triggered by the onfinish event handler to monitor the animation's progress.

For more information on the Web Animations API, visit: https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API

If you need to support older browsers, you can use this polyfill: https://github.com/web-animations/web-animations-js

Alternatively, you can utilize DOM events:

window.onload = function() {
  var elm = document.querySelector('.marquee'); // get the DOM element with your animation

  elm.addEventListener('animationend', function(e) { 
    console.log('This fires when the animation ends');
  });
  elm.addEventListener('animationstart', function(e) { 
    console.log('This fires when the animation starts');
  });
}

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 is the process for modifying the attributes of a currency text box in a Dojo within XPages?

I have come across several discussions aimed at addressing this issue, but none of them have provided a clear and definitive solution that I can easily follow. Is there a straightforward method to modify the css of a dojo field within XPages? Specifically ...

Display a notification to the user prior to reloading the page

I have created a code for logging attendance at work using a barcode reader. The user simply needs to scan their card with a barcode to register their attendance. let $scannerInput = $(".scanner-input"); $(document).ready(function(){ $scannerInput.focu ...

Using Node.js to integrate Stripe payment method

After successfully implementing a stripe payment method with node and express, I encountered some issues. Although the payment runs smoothly and returns a success message, the customer is not being added to the list of stripe customers. Additionally, my no ...

The command 'vue' is not a valid internal or external command

After ensuring that everything was installed correctly, I encountered an issue when trying to create a project. An error message would appear stating that "'vue' is not recognized as an internal or external command". I attempted to reinstall the ...

Send an unchangeable list to a component that needs an Array

Just diving into the world of React and learning that using .toJS() is not recommended due to its impact on performance. The dilemma I'm facing is that a third-party component I'm using requires an array as props, while my state is stored as an ...

Using the 'active' class in Bootstrap-4 Navbar specifically for the parent element

As I style the navbar in Bootstrap 4, I encounter an issue with dropdown items. Specifically, when I apply the 'active' class to highlight a dropdown item, all sub-items (children) end up with the same highlighting effect. This results in an unap ...

Using the Ruby on Rails redirect_to method

Imagine I have the following line in my controller: redirect_to "/sessions/attempt", provider: 5 Now, this is what my attempt.html.erb looks like: <h1>attempt</h1> <%= provider %> It's clear that this setup isn't functioning ...

Refreshing the previous tab upon changing tabs in React Navigation TabNavigator

I am currently working with a route structure that looks like this: StackNavigator -StackNavigator -TabNavigator --Tab1 ---Route 1 (Stack) (initial) ---Route 2 (Stack) --Tab2 ---Route 3 (Stack) (initial) ---Route 4 (Stack) The issue I am facing is that ...

Adjust the alignment and floating of text within an iframe on the same domain

Is it possible to align text on the right side of an iframe that contains a width and text inside? The iframe's src is from the same domain. If so, how can this be achieved through JavaScript? ...

"Angular: Enhancing Functionality with Nested Controllers and Service Dependency Handling

Hey there! I've got a setup with nested angular controllers. The outer one is called personController, while the inner one is personScheduleController. In this arrangement, the person controller reaches out to a service to retrieve person data. On the ...

Is it possible to modify an HTML document on the server side using Node.js?

I am currently working on a website project. As part of this project, there is a Python script that is activated by the user through the UI and runs on the server to generate HTML files. These HTML files are then read by the node server and sent in full to ...

How can I retrieve a formController in AngularJS?

When trying to reset the data in a form and calling form.setPristine(), I encounter an issue where the formController is not registered within the $scope. It may sound like a basic question, but how can I locate the formController? Within the code snippe ...

Can a condition be incorporated in a gulpfile to execute a task depending on the size of a file?

Currently, I am utilizing gulp for image compression. However, my requirement is to only compress images exceeding 200kb in size. Can JavaScript be used to loop through a directory and selectively run the minification process on files larger than 200kb? ...

Exploring Vue Components Through the Global Scope

Is it feasible to retrieve an instantiated Vue.js component object from the global JavaScript scope with Vue.js, or are these objects encapsulated within Vue's internals? For instance, when I have code defining a component like this: Vue.component(&a ...

What is the best way to attach a click event listener to dynamically generated child elements?

My parent container houses a variable number of elements generated by an API as the user inputs text. These elements, in turn, serve as parents to other child elements. The goal is for an overlay with more details about a specific element to appear when t ...

Looking to update the URLs in the text data to a different value

I am facing an issue with a list of links stored in a string. var data='<ol> <li><a href="#/getpage/getData/1">A Christmas Carol</a></li> <li><a href="#/getpage/getData/2">Copyright</a></li ...

What steps can I take to ensure my code runs smoothly from a USB across all devices?

My code for a concept website is stored on a USB stick, but I'm facing a problem with my buttons being anchored to a G: drive on Windows. However, when I use a Chromebook, the USB stick is recognized as removable media and not a G: drive, causing the ...

Converting JavaScript JSON into a PHP array

When working with Javascript, I create an array using the following code: cachePHP = "'lat':'" + (Number(upDataItems[2])).toFixed(5)+"'"; cachePHP = cachePHP + ",'lon':'" + (Number(upDataItems[3])).toFixed(5)+"' ...

The elements on the webpage are spilling over with content

I encountered an issue while creating a dashboard with a sidebar on the left side. When adding content to the page, some of it ended up hidden behind the sidebar. I tried using overflow-x:auto and this was the result: https://i.stack.imgur.com/5qHJY.jpg Be ...

Increase resolution of game canvas to support high definition (retina) display

In order to enhance the resolution of my game canvas and make it retina-quality, I am using Gamemaker software. However, I am unsure of how to actually implement this upgrade. If you are facing a similar issue, these two resources provide clear explanatio ...