Is there a way to utilize JavaScript in order to trigger a CSS animation to occur at a designated time during a video

I have a cool animated image element that I want to play at a specific point in time during a video using JavaScript. I'm not sure how to make it happen, but I know the .currentTime property could be the key. My goal is for the animation to only play once and if the user skips ahead or replays the video, the animation will trigger again.

I've created the animation CSS code below for reference:

body {
  background-color: grey;
}

video {
  width: 600px;
}

.inner {
  position: relative;
  height: 1000px;
  width: 1000px;
  overflow: hidden;
}

.animation {
  width: 200px;
  position: absolute;
  z-index: 1;
  left: 500px;
  top: 100px;
  animation-name: fling;
  animation-duration: 2s;
  visibility: hidden;
  overflow: hidden;
  animation-timing-function: linear;
}

@keyframes fling {
  0% {left: 500px;top:100px;visibility:visible;}
  20% {left: 800px;top:10px;transform:rotate(360deg);}
  40% {left: 1100px;top:100px;transform:rotate(-180deg);}
  42% {visibility:hidden;}
  100% {visibility: hidden;}
}
<body>
  <center>
    <div class="inner">
      <video controls autoplay>
        <source src="missile.mp4" type="video/mp4">
      </video>
      <img class="animation" src="https://paulgo.io/image_proxy?url=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FFQ_yFiLXMAAJmW9%3Fformat%3Dpng%26name%3Dlarge&h=d8af5114b1bd85e1d64353e43be2f4c1ea2edfc90479d4e7a12270ee9974616e">
    </div>
  </center>
</body>

Answer №1

If you want to constantly monitor the current time and apply an animation to an image, you can utilize window.setInterval() in the following way:

let vid = document.getElementById("videoID");
let animateTime = 100;
let i = window.setInterval(() => {
    if (vid.currentTime >= animateTime) {
        document.getElementById("imageID").classList.add('animation');
    }
},100);

In order for this to function properly, adjustments need to be made to the HTML by removing any existing animation classes from the image and assigning IDs to both the video and the image elements:

<video controls autoplay id="videoID">
    <source src="missile.mp4" type="video/mp4">
</video>
<img id="imageID" src="https://paulgo.io/image_proxy?url=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FFQ_yFiLXMAAJmW9%3Fformat%3Dpng%26name%3Dlarge&h=d8af5114b1bd85e1d64353e43be2f4c1ea2edfc90479d4e7a12270ee9974616e">

To ensure the animation is applied each time the video is replayed, you can incorporate the seeked event listener:

vid.addEventListener('seeked', () => {
    document.getElementById("imageID").classList.remove('animation');
})

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

Who is the father of Bootstrap Popover?

I'm currently facing an issue with getting a popover to be placed within a specific element. As of now, the popover is being inserted directly into the <body>, but I require it to be relative to other elements. I have been unable to locate a met ...

Angular - a simple method to determine the number of non-empty inputs in a complex template-driven form

As I work on multiple substantial Angular 11 template forms containing basic inputs like text, radiolists, and checkboxes, I am looking for the most effective method to calculate the percentage of completed inputs while the user is actively engaging with ...

a guide on showcasing a table according to a specific column's data (CSV Path)

I currently have a table structured like this: File Name File path MyFile1.csv D:\tmp\MyFile1.csv MyFile2.csv D:\tmp\MyFile1.csv As of now, my primary table is displayed as shown below: <div class="panel-body table-res ...

Guide on replacing buttons with <a> tags in express.js posts

I've incorporated handlebars as my chosen templating engine and I'm utilizing buttons to trigger app.post() in my JavaScript file. <form method="POST" action="/smo_assessment"> <div class="container" id="div1"> <h3 id="header" ...

What is the best method to loop through this object with JavaScript?

Suppose I have the following data: let testData = { 'numGroup1': [[(1, 2, 3, 4, 5), (5, 6, 7, 8, 9)]], 'numGroup2': [[(10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]] }; What is the best approach to iterate through this data using Jav ...

Navigating to a particular div using a click event

I am trying to achieve a scrolling effect on my webpage by clicking a button that will target a specific div with the class "second". Currently, I have implemented this functionality using jQuery but I am curious about how to accomplish the same task using ...

Navigate divs with varying z-index values

I want to change the z-index of 3 divs by toggling them using jQuery, but I'm not sure how to do it. What I want is to click a button that relates to a specific div and increase the z-index of that div so the content inside it is shown. Currently, all ...

Using the scroll feature within the tooltip component in React with @material-ui/core/Tooltip can cause the entire page to

I am currently working with a tooltip created using the @material-ui/core/Tooltip library, and it is functioning correctly. You can see an example of the tooltip in action at this link: https://codesandbox.io/s/kgccc. https://i.stack.imgur.com/fMgGb.png ...

Provide input to npm when running "my command" and utilize that input within my functions

Consider the contents of app.js const { doCoolStuff } = require("./api/myApi"); // grab parameter from command line and store it in "myParam" doCoolStuff(myParam); ... // more code And Package.json: { "name": "------ ...

Is the controller of a nested view in Angular UI router automatically considered a child of the parent view's controller?

My UI-Router setup includes a main view for products and two nested states below it. I want each nested view to have its own controller while also inheriting some basic information from the parent controller (productsCtrl). However, when attempting to acce ...

Monitoring the sharing of content on social media networks, rather than tracking individual

After setting up a hidden page on my site and configuring buttons to test pushing data to the dataLayer, I have ensured that my Google Tag Manager (gtm) is functioning properly. I recently tracked a Google +1 button click successfully, confirming that my c ...

Tips for integrating a vertical menu with button icons and subcategories

Currently working on a project with Twitter Bootstrap and looking to create a specific sidebar setup. My goal is to include subcategories using an accordion and a collapsible menu for mobile devices. I came across a similar implementation at http://jsfiddl ...

Using a self-invoking function in JavaScript with addEventListener

I'm struggling to get an Event Listener to self invoke a function and work correctly. Although the following code runs the function, the Event Listener is not functioning as expected: window.addEventListener("resize", (function () { document.getElem ...

Exploring the nuances of receiving responses with NextJs, Nodemailer, and Fetch

Currently in the process of constructing a basic contact form with Next.js, nodemailer, and fetch. Despite successfully sending emails from the frontend form to the designated email account, the network shows the contact submission as pending. After approx ...

Experimenting with NGXS selectors: A comprehensive guide

Hey there, I am currently utilizing the NGXS state management library in my application. I have a selector set up like this and everything seems to be functioning correctly. However, while testing the app, I encountered the following error message: "PrintI ...

Preventing the upload of empty images in an angular application

When selecting multiple images for upload, I sometimes need to make changes or delete the chosen images before actually uploading them. However, if any of the selected images have a size of 0B, I want to stop the upload process for all images, not just the ...

The div seems to be resistant to centering no matter the effort. Applying padding doesn't seem to be the solution, and even setting

I often come across this question but I can never seem to find the answer when it comes to padding or margin. It's strange that I'm having trouble properly centering the ul element within the div, especially considering that the div needs to be i ...

Sorting through a list of strings by checking for a specific character within each string

After spending years dabbling in VBA, I am now delving into Typescript. I currently have an array of binary strings Each string represents a binary number My goal is to filter the array and extract all strings that contain '1' at position X I ...

Pass data from controller using Ajax in CodeIgniter

Here is my JavaScript code: $(document).ready(function(){ $("input[type='checkbox']").change(function(){ var menu_id = this.value; if(this.checked) var statusvalue = "On"; else var statusvalue = "Off"; $.ajax( ...

What is the best way to arrange images in a 3 by 3 grid, beginning at position 0, using JavaScript to control navigation through button clicks?

When I click on button 1, it starts at image 1 because the counter is set to 0. Clicking on button 2 takes me to image 4 with a counter value of 3, while clicking on button 3 leads to image 7 with a counter value of 6. The process should also work in reve ...