Utilizing JavaScript to dynamically alter the animation property within CSS

How can I adjust the number of steps in an animation property set within a CSS file?

This is the CSS code I am using:

#ManSprite{
    overflow:hidden;
    width:200px;
    height:200px;
    position:absolute;
    top:280px;
    left:140px;
    background-image: url("images/ManSprite.png");
    z-index:99;
    animation: play .4s steps(2) infinite;
    -webkit-animation: play .4s steps(2) infinite;
    -moz-animation: play .4s steps(2) infinite;
    -ms-animation: play .4s steps(2) infinite;
    -o-animation: play .4s steps(2) infinite;
}

@keyframes play {
   from { background-position: -200px; }
     to { background-position: -600px; }
}

@-webkit-keyframes play {
   from { background-position: -200px; }
     to { background-position: -600px; }
}

I have tried two different methods to change the number of steps required for the animation.

var ss = document.styleSheets[0];

for(var i =0;i<ss.cssRules.length;i++){
    if(ss.cssRules[i].selectorText === "#ManSprite"){
        ss.cssRules[i].styles.animation = "play .4s steps("+stepsArray[StoryPart]+") infinite";
        ss.cssRules[i].styles.MozAnimation = "play .4s steps("+stepsArray[StoryPart]+") infinite";
        break;
    }
}

Additionally, I attempted another approach as shown below:

var steps = stepsArray[StoryPart];
$('ManSprite').css({"animation": "play .4s steps("+steps+") infinite",
                        "-webkit-animation": "play .4s steps("+steps+") infinite" ,
                        "-moz-animation": "play .4s steps("+steps+") infinite",
                        "-ms-animation": "play .4s steps("+steps+") infinite",
                        "-o-animation": "play .4s steps("+steps+") infinite"});

Unfortunately, neither of these methods were successful in changing the step count in the animation.

Answer №1

Unsure of the purpose of 'steps(2)' in this code snippet - it may be best to modify only this particular element using the .css() method. However, if you wish to make changes to animations specified in the CSS, resetting the animation is necessary. Here's how you can do it:

CSS (replace '#ManSprite' with '.animation'):

.animation{
  overflow:hidden;
  width:200px;
  height:200px;
  position:absolute;
  top:280px;
  left:140px;
  background-image: url("images/ManSprite.png");
  z-index:99;
  animation: play .4s steps(2) infinite;
  -webkit-animation: play .4s steps(2) infinite;
  -moz-animation: play .4s steps(2) infinite;
  -ms-animation: play .4s steps(2) infinite;
  -o-animation: play .4s steps(2) infinite;
}

@keyframes play {
   from { background-position: -200px; }
     to { background-position: -600px; }
}

@-webkit-keyframes play {
   from { background-position: -200px; }
     to { background-position: -600px; }
}

To start the animation:

$('#ManSprite').addClass('animation');

To change the animation:

$('#ManSprite').removeClass('animation').css(
    'animation-timing-function','steps('+steps+')' );
$('#ManSprite').addClass('animation');

These adjustments should ensure that everything works properly.

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

Why is the 'Access-Control-Allow-Origin' header missing in the MEAN stack Facebook authorization error?

Currently, I am working on implementing Facebook authorization in my MEAN stack application. To achieve this, I am utilizing the passport and passport-facebook modules. It's worth mentioning that I have opted not to use jade or ejs, and instead sticki ...

JavaScript form not working on submission

When my form is submitted, a function is called that successfully redirects users on desktop to either the download-confirmation or download-failure page. However, when testing on mobile devices such as iOS and iPad, the redirection does not seem to work. ...

Troubleshooting my unresponsive bootstrap drop down

I recently tried to implement a Bootstrap 4 drop-down list using code from w3schools.com in my visual studio code, but unfortunately, it's not functioning as expected. Surprisingly, the same code works perfectly fine in an online editor. I'm new ...

Introducing unnecessary DOM elements when displaying flash messages

When a user saves in my Rails application, it triggers an Ajax request to save the post and then runs the update.js.erb file. This file contains some jQuery code: $('body').append('<div class="message">Saved</div>'); Due t ...

Using jQuery to generate several div elements inside one main div

Given the parent div structure: <div class="large-9 columns"></div> I intend to add multiple child divs inside the parent: <div class="large-9 columns"> <div>JSON data point 1</div> <div>JSON data point 2</ ...

What causes the Top Navbar in Twitter Bootstrap to exceed the container when fixed?

While working with the default fixed-top navbar in Bootstrap, I encountered an issue where it spans the full width of the viewport. In order to contain it within a specific container div, I tried applying a CSS override for the left side: .navbar-fixed-to ...

Tips for eliminating unwanted white space underneath your webpage while zooming on a mobile device

Currently developing a responsive website, everything is running smoothly except for one issue. When I pinch zoom in on mobile and scroll down, a large white bar appears below the entire page, stretching across the screen width. How can this be fixed? Belo ...

How can I retrieve a single row at a time using mysqli_fetch_array function?

In my PHP code, I have created a quiz to display one question and four multiple choices on an HTML page using AJAX and jQuery. While I know how to use a while loop to display all the questions at once, I am unsure of how to show only one question at a time ...

Problem with the hover functionality of the <li> tag

I'm having an issue with applying the hover property to the li element in the sidebar. The hover effect works, but the icon tag is not showing the hover effect. I want the icon to also show the hover effect along with the li's hover effect. Here ...

Exporting GLTF/GLB files using ThreeJS: Rethinking the Structure of Scenes

When exporting my scene, I follow a simple method: function save(blob, filename) { const link = document.createElement("a"); link.href = URL.createObjectURL(blob); link.download = filename; link.click(); URL.revokeObjectURL(link); } fu ...

How to handle the "subscribe doesn't exist on type void" error when trying to subscribe to data from a service?

I am currently working on an Angular 7 application and I have encountered an error stating that the property 'subscribe' does not exist on type void when trying to subscribe to data from a service. The error is displayed in the subscribe data fu ...

Is it possible to utilize AJAX to split the text into two separate boxes instead of just one?

My HTML page is currently set up to fetch information from a database table and display it in a single text box. This process involves connecting to a PHP file using an AJAX function for handling the request. Now, I am considering the possibility of displ ...

What is the best way to make my JSON data trigger an alert when the button on my HTML page is clicked?

I've been working hard to display JSON data containing information about the school name, degree type, semester enrollment, courses, and student details. However, I'm facing an issue where nothing happens when I click the button linked to a click ...

Best practices for effectively managing a sizable dataset in Vue.js

My task at hand is to create a visualization dashboard that can operate solely in the browser, utilizing Vue.js, D3, and JavaScript. The dataset I am working with is stored in a .json file that is 48 MB in size. However, upon parsing the file using d3.json ...

Error: Cannot locate the named export 'remove' in Apollo Client

As I work on developing an apollo client plugin for a Nuxt 3 application, I encountered an error related to a package named ts-invariant: file:///Users/[my name]/Repositories/[project]/node_modules/@apollo/client/utilities/globals/fix-graphql.js:1 import { ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

The footer seems to be malfunctioning

Let's start with the code: CSS: *{ margin:0; padding:0; } body,html{ height:100%; } body{ background:url('../images/bg.png'); background-position:center; background-repeat:no-repeat; background-attachment:fixed; height:100%; ...

Attempting to use jQuery on click to set the background image of a div to a base64 encoded data image

Check out what I'm working on here The first div contains html with data:image;base64 <div id="large_photo_null" style="width:50px; height:50px; background-image: url( data:image;base64,R0lGODlhR.. );" > </div> When using html, the ba ...

Can anyone help me determine the reason why my CSS is being displayed as struck-through in Google Chrome?

After successfully running my app on localhost, I encountered CSS issues when deploying it on Heroku. Some of the CSS appears as struck-through in Chrome. How can I identify what is overriding my styling? https://i.sstatic.net/U23fg.png ...

For all URLs, redirect from HTTP to HTTPS unless the request is coming

I recently transitioned my node.js app to use https. To achieve this, I configured https through an nginx reverse proxy. However, I encountered a problem where, when I type in example.com, it does not automatically redirect to https://example.com. In an at ...