Manipulating CSS animations using JavaScript

Recently, I've been working on a basic keyframe animation. The animation is set to blink truck lights:

animation: blink-truck-lights .4s 8s 10s steps(2) 2 forwards;
@keyframes blink-truck-lights {
 from{background-position: 0px 0;}
 to{background-position: 0px -250px;}
}

Next, let's take a look at the JavaScript portion:

setInterval(function(){
 $('#truck').addClass('blink-truck-lights');       
},500);

setInterval(function(){
 $('#truck').removeClass('blink-truck-lights');       
},800);

My goal is to make this animation play over a specific interval of about 8 seconds. Initially, I thought of adding and removing the class with the animation syntax, but when I attempted to use setInterval for that purpose, the animation didn't start as expected.

Answer №1

You have the option to achieve this using solely CSS.

#id {
  -webkit-animation: NAME-YOUR-ANIMATION 8s infinite; /* Safari 4+ */
  -moz-animation:    NAME-YOUR-ANIMATION 8s infinite; /* Fx 5+ */
  -o-animation:      NAME-YOUR-ANIMATION 8s infinite; /* Opera 12+ */
  animation:         NAME-YOUR-ANIMATION 8s infinite; /* IE 10+ */
} 

LINK

UPDATE 2:-------------------------------------------------------------------------

If you prefer a Javascript solution, here it is:

function blink()
        {       
document.getElementById('blink').className = "animated blink_css";
        }

setInterval(function(){
blink();
},8000)

To implement the animation in CSS:

      @keyframes 'blink' {
     //your code for animation
                         }

    //try moz for mozilla,o for opera and webkit for safari and chrome 
        .blink_css {
            -webkit-animation-name: blink;
            -moz-animation-name: blink;
            -o-animation-name: blink;
            animation-name: blink;
                   }

        .animated {
            -webkit-animation-duration:8s;
            -moz-animation-duration:8s;
            -ms-animation-duration:8s;
            -o-animation-duration:8s;
             animation-duration:8s;
                  }

UPDATE 3:-------------------------------------------------------------------------

.paused{
    -webkit-animation-play-state:paused;
    -moz-animation-play-state:paused;
    -o-animation-play-state:paused; 
    animation-play-state:paused;
}

Simply add or remove this class as needed. Hopefully, this information will be helpful. Cheers!!!

Answer №2

Here's a simple method to achieve the same effect without relying on animationEnd or animationStart events. All you need to do is toggle a CSS class on the target element and specify the interval for the animation to restart.

setInterval(function(){$('#car').toggleClass('blink-car-lights')},10000);

Now, watch as the car lights blink every 10 seconds like clockwork.

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

Is the event loop blocked by setTimeout() in Node.js?

Is it true that if I have a basic setTimeout() function set for 10 seconds, the entire server will crash during that time? I heard rumors about this. ...

Issue: Unable to assign type 'FormDataEntryValue' to type 'string'. Type 'File' cannot be assigned to type 'string'

After retrieving data from the formData, I need to pass it to a function for sending an email. Error: The error message states that 'FormDataEntryValue' is not compatible with type 'string | null'.ts(2322) definitions.ts(119, 3): The e ...

Ajax pagination does not update the currently active link

Hello, I am attempting to implement ajax pagination using CodeIgniter. However, I have encountered an issue where the active link in the pagination does not change. Can someone please assist me with this problem? Here is my AJAX code: $(function() { a ...

Reposition UVs in Vertex Shader to maintain texture integrity without causing distortion

I'm working on rotating and scaling UVs in a vertex shader to ensure that the rotated texture completely fills its available bounding box. My current implementation is successfully rotating and auto-scaling the texture, but I'm facing an issue wh ...

Instructions on keeping a numerical counter at its current value for all site visitors

Recently, I integrated a number counter into my website. However, I am facing an issue where the count resets to zero whenever a new visitor accesses the site. I'd like the count to remain persistent and update based on the previous count. For instanc ...

If the desktop website is zoomed in beyond 150%, it will automatically switch to mobile responsive mode

Whenever the desktop website is zoomed above 150%, it automatically switches to mobile responsive mode. Is there a way to disable this feature? You can find the website in question here: Give it a try by zooming to 150 percent and see for yourself. Appr ...

Dismiss MUI Snackbar notification and execute action upon pressing a key

A custom notification system has been developed, utilizing the material ui Snackbar with both an action button and a close button. The objective is to implement a listener event for the "enter" key in order to trigger the specific notification's actio ...

Tips for adjusting the border radius of a dropdown box on a Bootstrap website within the CodeIgniter framework

I attempted to use CSS in order to achieve rounded corners for my dropdown box, but unfortunately it didn't have the desired effect. What I am aiming for is to round the corners of my dropdown box, similar to a search bar or search button. https://i. ...

When Vue.js is compiled, it removes a script tag

I'm currently learning Vue.js and encountering an issue that I can't seem to resolve. My project is utilizing Vue CLI 3, and within my code I am inserting a custom tag (not a component) in my template with a script tag inside it. <ra type="ou ...

save information in javascript variable using JSON syntax

I am currently working on obtaining address values from geolocation in my JavaScript code. Here is the script I have so far: function getLocation() { if (navigator.geolocation) { navigator.geolocation.watchPosition(showPosition); } else { ...

Troubles with Angular elements not aligning correctly when using the "display: block" property

When using an angular element for a directive with "display: block", it may not automatically take up 100% of the width of the parent container. In order to ensure that it does, the width must be explicitly set to "100%" in the CSS. Despite setting "width: ...

Struggling to make the image adapt to mobile screen sizes, even after applying a width of 100% and

After spending countless hours researching online, I still can't figure out how to make the image responsive on mobile devices. On a computer screen, it looks fine: https://i.sstatic.net/sCPbA.png However, when I inspect the element and view the ima ...

Session values do not persist in Window Popups

While the system functions properly in the main window, there is an occasional issue when generating a bill through AJAX. After generating the bill, a window popup automatically opens to display the bill details. However, during this time, the login sess ...

Bootstrap modal fails to appear on the screen

I am in need of assistance. I have a bootstrap template with a footer, and I am trying to integrate a modal. However, when I click the modal button, the modal does not appear. Is there a missing plugin that needs to be added to my template? <script sr ...

What is the best way to make an element "jump to the top" when the parent element has reached its maximum height?

I have a parent div containing 6 child divs. The height of the internal divs changes dynamically based on the data. The outer div has a fixed height set. I want the internal divs to move to a new column inside the parent div when they no longer fit in term ...

How can I use jQuery to save different types of files like pictures and PDFs as 'mediumblob' in a MySQL database?

I am currently developing a tool for assessments and have encountered an issue with the logic: Whenever I click on 'Upload/View Files' within each question, a modal window pops up; Within the modal window, there is a section where you can s ...

Looping through properties of objects with the help of angularJS ng-repeat is known as using objects['propertyname&#

What is the best way to iterate over an object with property names like this? $scope.myobjects = [ { 'property1': { id: 0, name: 'someone' } }, { 'property2': { id: 1, name: ' ...

Why does my AJAX request keep returning a 500 internal error in Laravel?

My goal is to verify the username when a new user is entered, using AJAX so that the correct username can be displayed in the field. Form <form role="form"> <input type="hidden" id="token" name="_token" ...

What is the best way to define a color for a class in Vue?

src/components/HelloWorld.vue <template> <div class="h-screen flex"> <div class="w-1/2 bg-gradient-to-r from-green-500 to-blue-900"></div> <div class="w-1/2 bg-beige"></div> < ...

What is the best way to center card-columns on a webpage while using bootstrap version 4.3.1?

I am attempting to center a card-columns horizontally using Bootstrap 4.3.1 while nesting cards. Below is the structure of my nested cards: > Main Card >> Card-columns >>> Card 1 >>> Card 2 >> ...