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

Having difficulties retrieving the value of the div in the voting system

Whenever the element with the id #upvote is clicked, the value of the element with the id #vote increases by 1. On the other hand, when the element with the id #downvote is clicked, the value decreases by 1. However, there seems to be an issue where if the ...

Tips for displaying a React component with ReactDOM Render

_Header (cshtml) <div id="Help"></div> export default class Help { ReactDOM.render( <Help/>, document.getElementById('Help') ); } Help.js (component) } My objective is to di ...

"Is it possible to conditionally render a component depending on the state in

One of the challenges I'm facing is customizing a filter icon from MaterialUI. My goal is to change its color to black when a checkmark is checked, and adjust its position accordingly. Additionally, when a box is checked, it should fill in setFilters. ...

`Angular2 - exploring the complexities of function scope`

I'm facing a challenge while working on my Angular2 Sample with the http module. Here is a snippet from my component: app.loginComponent = ng.core.Component({ selector: 'login', templateUrl: 'app/login/login.html&ap ...

Auto-selecting the first item in a CSS menu when the switcher is tapped on mobile devices

Struggling with a responsive CSS menu on my website, . The switcher on mobile seems to automatically click the first item in the menu (Home) as I open it, redirecting me instantly. When setting the link to "#" everything is fine, but then I lose the home l ...

What could be the reason for justify-self: flex-start not positioning the div at the bottom of a column?

I want to display a div in three levels: header, content, and footer. The content can vary in height and the footer should always be at the bottom. Here is how I have implemented it: <div class="news-content-block"> <div class=" ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

Searching for all potential arrays of length L that total N or fewer can be achieved using an algorithm

In JavaScript, I am looking for a way to discover all potential arrays - consisting of non-negative integers - with a size L that add up to - at most - N: function findArrays(size, maxSum){} For example: findArrays(3, 2) Sample output: [[0,0,0], [0,0,1], ...

Update the color of navigation items to reflect their active status

Here is the snippet of HTML code: <header> <nav> <a href="#" id="menu-icon"></a> <ul> <li><a href="#"">Home</a></li> <li><a href="#">About</a></li> & ...

I'm having trouble applying JavaScript to my Flask template, even though it is stored in the static directory. Any suggestions on how to fix this issue with the code provided?

I am currently working on a Flask project and attempting to create a hierarchical structure resembling a tree. However, I suspect that the JavaScript is not being correctly applied to my tree.html file, as the options cannot be expanded. The code provided ...

Encountering an Enumeration Exception when trying to delete an element from a collection list using a foreach loop

I encountered an issue when attempting to remove an element from a list collection using foreach. I have searched online but have not found a clear explanation for the problem. If anyone has knowledge about this, please share the information. ...

Leveraging the Google Geocode API through HTTP GET requests

I am facing a challenge in my HTML file where I have a map and I am using HTTP get with jQuery to retrieve a device's location. However, I am struggling to plot this location on the map. I need to parse the location information and display it accurate ...

"Troubles with directing on websites using jQuery, CSS,

I have been struggling with creating this navigation bar for weeks now and I keep running into issues. What I am attempting to achieve is a primary navigation bar that, when hovered over, displays a secondary navigation menu below and slightly to the righ ...

Troubleshooting problem with decrypting data using CryptoJS AES256

I am currently facing an issue with the decryption of a URL that has been encoded using AES256. I am using CryptoJS for the decryption process, but I keep encountering the following exception: Malformed UTF-8 data Have I missed something in the code? rout ...

The auto setting in the CSS clamp function is not functioning properly when used as the minimum, value,

I have been trying to use the css function clamp() to control the height of my div, but for some reason it is not behaving as I expected. .container{ height: clamp(200px, auto, 400px); } Interestingly, it works perfectly fine when I define the heights ...

Trouble obtaining AJAX result using onClick event

As a newbie to AJAX, I am still trying to grasp the concept. My task involves using an AJAX call to extract specified information from an XML file. Even after carefully parsing all tag elements into my JavaScript code, I encounter a problem when attempting ...

Automated method for triggering button clicks on a webpage using JavaScript with a tailored combination of unique tag and class name

Currently, I am exploring methods to automatically trigger a button click on a webpage with a specific tag and class. My approach involves using Tampermonkey (Javascript userscripts) to accomplish this task. Referencing the image of the CSS/HTML elements r ...

Error in Mongodb: Unable to convert value into ObjectId

Currently, I am attempting to retrieve only the posts belonging to users using the following code snippet: router.get("/:username", async (req, res) => { try { const user = await User.findOne({ username: req.params.username }); const ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

How can you extract the property names of the first object in an array of objects?

I have an array of objects with the following structure and I want to extract the property names of the first object from this array without including the values. The desired result should only be ["Name", "Account", "Status"] ...