Toggle between pausing and running CSS animations with this handy button!

My awesome graphic animation is in CSS and SVG format. I've been struggling to add a play/pause button to control the animation on click. Here is what I have so far:

    .animation1 {
        --animation-delay: 0.1s;
        animation: ani_keyframes 1.8s linear infinite var(--animation-delay) paused;
    }
    
    .playani {
        animation-play-state: running;
    }
    
    .animation1:hover {
        animation: none;
        fill: #666;
    }

@keyframes ani_keyframes {
...
...

}

<script type="text/javascript">
    var button = document.getElementById('button-ani'),
        test_ani = document.getElementByClassName('animation1');
    
    button.onclick = function(){
      test_ani.classList.toggle('playani');
    }
  
</script>
  
<div id="animation1_wrapper">

<svg id="animation1" width="100%" height="100%" viewBox="0 0 418 255" fill="none" xmlns="http://www.w3.org/2000/svg">
    
    <g id="ani_graphic">
<path class="animation1" d="M263.46 25.3801C257.63 29.2001 252.88 33.7801 249.33 37.8001H263.46V25.3801Z" fill="#000"></path>
.....
.....
.....
</g>
</svg>
</div>

 <button id="button-ani">Toggle Animation Play State</button>

Answer №1

When you use document.getElementsByClassName('animation1'), you receive an HTMLCollection object. However, ClassList applies to specific elements, so you need to select the element by using an indexer to make your code function correctly.

var button = document.getElementById('button-ani');

var test_ani = document.getElementsByClassName('animation1');
// You need to use [0] to access the element from the HTML collection obtained.

button.onclick = function(){
  test_ani[0].classList.toggle('playani');
}
.animation1 {
      --animation-delay: 0.1s;
      animation: ani_keyframes 1.8s linear infinite var(--animation-delay) paused;
  }

  .playani {
      animation-play-state: running;
  }

  .animation1:hover {
      animation: none;
      fill: #666;
  }

  @keyframes ani_keyframes {
    from{
      transform:scale(0);
    }
    to{
      transform:scale(1.1);
    }

}
<button id="button-ani">Toggle Animation Play State</button>
<div id="animation1_wrapper">

<svg id="animation1" width="100%" height="100%" viewBox="0 0 418 255" fill="none" xmlns="http://www.w3.org/2000/svg">
    
    <g id="ani_graphic">
<path class="animation1" d="M263.46 25.3801C257.63 29.2001 252.88 33.7801 249.33 37.8001H263.46V25.3801Z" fill="#000"></path>
.....
.....
.....
</g>
</svg>
</div>

Answer №2

utilize

document.querySelector('.animation1');

rather than

document.getElementsByClassName('animation1');

I implemented a translate animation for illustration purposes. Hopefully, it functions as intended :).

var button = document.getElementById('button-ani');
var test_ani = document.querySelector('.animation1');
    
button.onclick = function(){
  test_ani.classList.toggle('playani');
}
.animation1 {
  --animation-delay: 0.1s;
  animation: ani_keyframes 1.8s linear infinite var(--animation-delay) paused;
}

.playani {
  animation-play-state: running;
}

.animation1:hover {
  animation: none;
  fill: #666;
}

@keyframes ani_keyframes {
  from{
    transform:translateX(0px);
  }
  to{
    transform:translateX(-100px);
  }

}
<button id="button-ani">Toggle Animation Play State</button>

<div id="animation1_wrapper">
  <svg id="animation1" width="100%" height="100%" viewBox="0 0 418 255" fill="none" xmlns="http://www.w3.org/2000/svg">
    <g id="ani_graphic">
      <path class="animation1" d="M263.46 25.3801C257.63 29.2001 252.88 33.7801 249.33 37.8001H263.46V25.3801Z" fill="#000"></path>
      .....
      .....
      .....
    </g>
  </svg>
</div>

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

Issue with custom font display malfunction

I'm having difficulty getting my custom @font-face to function properly. When I apply this class style to a <p>, it always defaults to Arial. Can anyone point out what might be going wrong here? <style> .stonefont @font-face { font-fa ...

Trigger $q manually in AngularJS

My understanding of $q in AngularJS is that it runs every time I refresh my page, similar to using a function in ng-init. Here is the code for $q.all that I have: $q.all([$scope.getCart(), $scope.getCategory(), $scope.getMenu(), $scope.getRestaurant()]). ...

Troubleshooting jQuery's issue with dynamically adding input fields

I came across a tutorial (which I tweaked slightly) on this website: code In JSFiddle, everything works perfectly fine with the code. However, when I implemented it on my actual page, it's not functioning as expected. I've been trying to trouble ...

Wordpress easily adjusts post alignments for a seamless display

Can anyone help me figure out how to properly align posts in Wordpress to match the example image attached? I've tried using inline-block or float with CSS/HTML, but the posts are not aligning correctly. I'm unsure of what this method is called s ...

changing a variable in javascript

Is there a way to successfully update the "storage" variable set in uploadify? I have a function called set_path that is designed to modify the variable by combining it with other values whenever specific content is selected. $(document).ready(function () ...

"Nested AngularJS controllers: a deep dive into the world

Recently, I've been delving into the world of AngularJS and I can't shake the feeling that my approach to the paradigm might be a bit off. I have a controller for managing panes (linked to an ng-repeat) which tracks which panes the user has open ...

How can you trigger a modal to appear when an image is clicked?

There are images inside <div> tags. When one of the images is clicked, a modal appears to display information about the specific image. Each modal has a unique id or class, such as modal4. My example: <image type="image" src="Images/Drake.jpg" ...

Displaying and Concealing Divisions

My journey to showing/hiding divs began with piecing together a series of questions: $(document).ready(function(){ $('.box').hide(); $('#categories').onMouseOver(function() { $('.box').hide(); $('#div' + ...

Bringing in d3js into Angular 2

Is there a way to successfully import d3js into an Angular2 project? I have already installed d3js using npm and added it to my systemJs, but am encountering a traceur.js error. I also attempted to just use the latest cdn in a script tag and tried import * ...

What is the best way to make sure that the parent div of an svg shows its shadow on top of the svg itself?

I am in the process of creating an interactive world map using an SVG map. The SVG format is necessary because I have implemented functionality to zoom in and move the map around. However, a challenge has arisen: the SVG element is obstructing the shadow o ...

The data retrieved from the $.ajax() request in Vue.js is not properly syncing with the table

After setting up an $.ajax() function and ensuring the data binding is correctly configured, I expected the data to append to a table on page load without any issues. However, the data is not appearing as expected. Is there something that I might be overlo ...

Executing processes individually within AngularJS

Just making sure I understand correctly, I have a simple web service resource query function set up like this //Get country lists $scope.getCountry = function(){ $http({ method : 'GET', url : cdnLinks('country&apos ...

From transitioning from a radio button's checked indicator to a complete button

I'm in the process of customizing my WordPress plugin and seem to be struggling with styling the radio buttons. For reference, you can find the code snippet here: https://jsfiddle.net/cd3wagvh/ The goal is to conceal the radio buttons and modify the ...

Leveraging the power of the vuejs plugin within the main.js script

My goal is to develop a plugin to manage the OAuth2 token data in my Vue.js application. I followed several tutorials available on the internet to create this plugin. var plugin = {} plugin.install = function (Vue, options) { var authStorage = { ...

What is the best way to transfer JSON data to a different controller in AngularJS?

Hello, I'm still learning AngularJS and facing an issue with the following code snippet. app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: "partials/home.html", controller: "mainControlle ...

The modal fails to display when the content is positioned below a setInterval function

i have created a notification system using ajax currently, I am attempting to open a modal by clicking on the content of the notification with setInterval the modal works perfectly when the content of my notification is not being updated via setInterval. ...

Utilizing unique symbols to dynamically add form elements to an HTML page with jQuery's append method

I am facing an issue with creating forms on my HTML page. Here is an example of how I am trying to do it: <form action="/tasks/<%= allTasks.e[0].id %>/delete" method="POST"> <button class="deleteTask">Delete</button> </f ...

Executing a JavaScript file within the Meteor JS ecosystem

Is there a way to execute a JavaScript file on the server side in a meteor JS environment? Providing some background information: I am looking to automatically insert a document into a mongo database. While I know how to do this in meteor through event-dr ...

Looking for a solution to a problem with your vertical CSS/jQuery dropdown menu

My web app features a vertical CSS menu that is working correctly except for one minor issue. When I mouse out on all elements with the class a.menutoggle, the last dropdown menu remains open. I am struggling to find a solution to hide it. Can someone plea ...

When the mouse leaves the area, I would like the iframe within the div to be refreshed

When you hover over the button on the right, a slide panel appears with an iframe. Each time this page loads, it has a different background. I want a new background to load every time there is a new hover, requiring a refresh of the div. How can I achieve ...