Is it possible for an animation to complete even if it is stopped midway?

I am currently working on a media player project where I have implemented a scrolling marquee effect for the song meta information using JavaScript and CSS. The scrolling effect only occurs when the track is playing, and I achieve this by adding/removing the animation class through JavaScript when the play/pause button is pressed. However, I am facing an issue where if the animation class is removed in the middle of the scroll, it stops abruptly. Is there a way to let the animation complete before stopping when the class is removed?

var MetaScroll = document.getElementById("MetaScroll");
        var PlayButton = document.getElementById("PlayButton");

        function playPause() {
          MetaScroll.classList.toggle('scrolling');
          PlayButton.classList.toggle('fa-play');
          PlayButton.classList.toggle('fa-pause');
        }
body {
          background: black;
        }

        .albumArt {
          width: 200px;
          height: 200px;
          border: 3px solid #212121;
          display: flex;
          flex-direction: column-reverse;
        }

        .metaContainer {
          height: 25%;
          overflow: hidden;
          background-color: white;
        }

        .meta {
          white-space: nowrap;
          height: 100%;
          display: flex;
          flex-direction: row;
          align-items: center;
        }

        .meta p {
          font-family: Courier, monospace;
          font-size: 20px;
          margin: 0;
          color: black;
        }

        .scrolling {
          transform: translateX(0);
          animation: b-text-scroll 5s linear infinite;
        }

        @keyframes b-text-scroll {
          0% {
            transform: translate3d(0, 0, 0);
          }
          20% {
            transform: translate3d(0, 0, 0);
          }
          100% {
            transform: translate3d(-100%, 0, 0);
          }
        }

        .pIcons {
          font-size: 20px;
          color: white;
          background-color: transparent;
          border: none;
        }
<script src="https://kit.fontawesome.com/1706aa300d.js" crossorigin="anonymous"></script>

          <body>
          <div class="albumArt">
          <div class="metaContainer">
          <div id="MetaScroll" class="meta">
          <p>&nbsp; The Absense of a Title - A Deadly Lack of Artist</p>
          <p>&nbsp; The Absense of a Title - A Deadly Lack of Artist</p>
          </div>
          </div>
          </div>
          <button class="pIcons" onclick="playPause()">
          <i id="PlayButton" class="fa-solid fa-play"></i>
          </button>
          </body>

Answer №1

If you want to enhance your current approach with a bit more logic, consider adding an animationend event listener instead of simply removing the class when paused. This way, you can remove the class when the animation end event triggers.

var MetaScroll = document.getElementById("MetaScroll");
var PlayButton = document.getElementById("PlayButton");

function playPause() {
    // To track whether it's a pause or play action
    if (pause) {
        MetaScroll.addEventListener('animationend', endAnimationAfterCompletion);
    } else {
        MetaScroll.classList.add('scrolling');
        MetaScroll.removeEventListener('animationend', endAnimationAfterCompletion);
    }
    PlayButton.classList.toggle('fa-play');
    PlayButton.classList.toggle('fa-pause');
}

function endAnimationAfterCompletion() {
    MetaScroll.classList.remove('scrolling');
}

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 should I do if one of my images fails to load after the previous one has loaded successfully?

My code is designed to create an animation using 3 canvases: one for the base image, one for the streamline wind map drawing, and another for an image covering part of the drawing. The following code displays the uploading of two images. var im ...

Learn the process of automatically copying SMS message codes to input fields in Angular17

After receiving the first answer, I made some changes to the code. However, when testing it with Angular, I encountered several errors. How can I resolve these issues? TS: async otpRequest() { if ('OTPCredential' in window) { const ab ...

Increase division height when mouse hovers over it

I want the height of the div to be 50px by default and change to 300px onmouseover. I have implemented this as follows: <style type="text/css"> #div1{ height:50px; overflow:hidden; } #div1:hover{ height:300px; } </style> <body> <div i ...

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

Place the menu on top of the div by adjusting the z-index

Hey there, I'm working on a project and I need help with an issue. You can check out the example page here: If you try to open the menu and click between "list" and "new ads", you'll notice that you're actually clicking on the dropdown se ...

Setting cookies in Express will not work if you are using res.sendFile()

After implementing the res.sendFile() function, I noticed that the set-cookie header is not being received in the response. app.get(sessionTracker, (req, res, next) => { res.cookie('tracker', '123a', { maxAge: 172800000, h ...

With Crypto-JS, a fresh hash is always generated

I'm looking to integrate crypto-js into my Angular 8 application. Here is a snippet of my code: import {Injectable} from '@angular/core'; import * as CryptoJS from 'crypto-js'; @Injectable() export class HprotoService { public ...

Seeking assistance in optimizing my Javascript code for more efficient canvas rendering

I've created a script for generating random moving lines as a background element for my portfolio. While it runs smoothly on its own, I encounter frame drops when combining it with other CSS animations and effects, especially at the beginning (althoug ...

What's the best way to trigger an event within a tag in a Vue.js component?

app.js Vue.component("popup",{ template : /*html*/` <div class="popup is-active" > <div class="popup-background"></div> <div class="popup-card"> <header class=" ...

Using xignite api to retrieve stock data

I've been encountering difficulties trying to make this JavaScript script function properly. Every time I attempt to run it, I receive an error message stating: "XMLHttpRequest cannot load" "No 'Access-Control-Allow-Origin' header is presen ...

Emptying the trumbowyg editor within an Angular environment

I am currently experiencing issues with the trumbowyg editor in a project I'm working on. I am able to update the editor by changing its model but cannot seem to clear its content using $scope.editorModel = '';. For a more detailed explanati ...

JavaScript's ability to call object properties at multiple levels allows for complex data

My approach involves using mongodb in conjunction with ajax calls for data retrieval. However, I have encountered an issue where the properties needed to generate HTML from JavaScript objects are sometimes missing. Consider this ajax call: $.ajax({ ...

How do you properly bind multiple events in jQuery and then unbind just a few of them?

Is it possible to bind multiple events, then unbind a couple of them? This is what I'm trying to achieve: When hovering over the element, the background color changes and changes back when hovering out. But when clicking the element, I want to disabl ...

Implementing OAuth2 in a Microservices architecture to establish a user account

In my current setup, I am utilizing a React Application along with a separate Express API. My goal is to allow users to register through my React app. To do this, I believe the oauth2 flows should follow these steps: Prompt the user for information (suc ...

Unable to trigger onSelect event on the datepicker component

Whenever a date is chosen, I need to trigger a javascript function. Here is the javascript code: $(document).ready(function(){ var date_input=$('input[name="date"]'); //our date input has the name "date" var container=$('.bootstrap- ...

Adjust the color of the text based on a conditional in react

I am looking for a way to select elements and change text color in my unordered list based on specific conditions. Below is an example of the structure I have: <div style={styles.passwordRules}> <ul style={styles.listOne}> <li style={ ...

Rotating an object around another object in a 3D matrix axis using Three.js

I currently have the ability to rotate one axis. Here is the code that's working now: https://codepen.io/itzkinnu/full/erwKzY Is there a way to rotate an object on a random axis instead of just one fixed axis? Maybe something similar to this exam ...

Make the most of your Bootstrap 3 layout by utilizing a full page container that fills both the width and height between a fixed header and

I am currently working on a basic bootstrap page with the Example template from Bootstrap's website. I want the content in the middle to take up the space between the header and footer, while ensuring that both the header and footer remain visible at ...

Altering an element's visibility from 'none' will trigger its animation to play once again

Take a look at the snippet below and you'll see that the sliding animation plays twice - once when the .addClass statement runs, and again when #test's display is switched to 'initial' (timeouts are in place to help visualize the issue) ...

Separate every variable with a comma, excluding the final one, using jQuery

I've developed a script that automatically inserts checked checkboxes and radio options into the value() of an input field. var burgerName = meat + " with " + bread + " and " + onion + tomato + cheese + salad; $('#burger-name').val(burger ...