leveraging javascript to manage the pause and play of CSS3 animations

I am attempting to create a CSS3 animation using pure JavaScript. The animation is working properly, but I now want it to pause when the mouse enters the container and resume running when the mouse leaves the container. I have tried using animate.pause, animate.play, and animationPlayState, but the functionality is still not working as intended. Can someone guide me on how to make it work correctly? Please excuse any language mistakes, thank you!


This is the code I have written:

window.onload = function() {
var ulNode = document.querySelector(".container>ul"),
frames = [
{left: 0},
{left: '-700px'},
{left: 0}
],
timing = {
duration: 10000,
iterations: Infinity,
};
ulNode.animate(frames, timing);
var player = ulNode.animate(frames);

ulNode.onmouseover = function(){
// player.pause();
this.style.animationPlayState = "paused";
}
ulNode.onmouseout = function(){
// player.play();
this.style.animationPlayState = "running";
}
}
body,ul{margin: 0; padding: 0;}
.container{
  width: 500px;
  height: 100px;
  position: relative;
  margin: 0 auto;
  overflow: hidden;
}
ul{list-style-type: none; position: absolute; left: 0; top: 0; width: 1200px;}
ul>li{width: 100px; height: 100px; float: left;}
ul>li:nth-child(odd){background-color: red;}
ul>li:nth-child(even){background-color: green;}
/*@keyframes doMove{
form{left: 0;}
50%{left: -700px;}
to{left: 0px;}
}
ul{animation: doMove 20s linear infinite;}
.container:hover ul{animation-play-state:paused;}*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8>
<title>CSS3 Animation</title>
</head>
<body>
<div class="container">
<ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</div>
</body>
</html>

Answer №1

It seems that the correct JavaScript syntax to pause an animation for Chrome, Safari, and Opera is:

 document.getElementById("myDIV").style.WebkitAnimationPlayState = "paused";

This information is based on a source from W3Schools. However, despite multiple attempts, I was unable to make it work as intended. (Refer to the code below)

window.onload = function() {
      var ulNode = document.querySelector("#container"),
      frames = [
        {left: '0px'},
        {left: '-700px'},
        {left: '-100%'}
      ],
      timing = {
        duration: 10000,
        iterations: Infinity,
      };
      ulNode.animate(frames, timing);

      ulNode.onmouseover = function() {
        document.getElementById("container").style.WebkitAnimationPlayState = "paused";
      }
      ulNode.onmouseout = function() {
         document.getElementById("container").style.WebkitAnimationPlayState = "running";
      }
    };
    
body,
    ul {
      margin: 0;
      padding: 0;
    }
    #container {
      width: 500px;
      height: 100px;
      position: relative;
      margin: 0 auto;
      overflow: hidden;
    }
    ul {
      list-style-type: none;
      position: absolute;
      left: 0;
      top: 0;
      width: 1200px;
    }
    ul>li {
      width: 100px;
      height: 100px;
      float: left;
    }
    ul>li:nth-child(odd) {
      background-color: red;
    }
    ul>li:nth-child(even) {
      background-color: green;
    }
    
<html>

    <head>
      <meta charset="utf-8">
      <title>CSS3 Animation</title>
    </head>

    <body>
      <div id="container">
        <ul>
          <li></li>
          <li></li>
          <li></li>
          <li></li>
          <li></li>
          <li></li>
          <li></li>
          <li></li>
          <li></li>
          <li></li>
          <li></li>
          <li></li>
        </ul>
      </div>
    </body>

    </html>

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

Reducing Bootstrap Navigation Bar with a scrolling logo

Is there a way to make the fixed navbar shrink 50% when it starts scrolling? I've only come across text navbars, but I'm looking for one with a logo. Any suggestions would be greatly helpful. You can access the css and html from that link. ...

Move two markers on Google Maps simultaneously

After researching various articles and posts on Stack Overflow about selecting multiple markers in Google Maps, I have been unable to find a solution for dragging two markers simultaneously. While I've managed to make it work so that one marker can tr ...

Fix surface orientations on potentially corrupted .stl files

I am facing a challenge in Three.js where I need to fix the normals on files that are coming in with potential issues. It's unclear whether the problem lies in the scanning process or during the file uploads. While we are investigating the upload func ...

"Utilizing Meteor to sort data regardless of letter case

How can I perform a case-insensitive sort of a Meteor collection? What additional code would be required in the following block? var movies = Movies.find({}, {sort: {name: 1}}); Alternatively, is using Underscore (or another vanilla JS method) on the f ...

HTML CSS list-style-position: outside not functioning as expected

I'm having trouble figuring out why the CSS property list-style-position: outside isn't working as expected. I've made sure to use the important tag and have included it in all my CSS classes, but for some reason, it's still not taking ...

Where should one begin when embarking on the journey to create a real-time chat application using react-native?

My goal is to create a basic chat room application with real-time message functionality. What key aspects should I prioritize and tackle first in this project? ...

What is the best way to eliminate duplicate items in JavaScript?

Note: I am aware that we use Set to eliminate duplicates in an array. I have a date dropdown. When I select a date, it displays the date correctly in a list. However, the problem arises when I select an already chosen date, it still shows up in the list. ...

.innerHTML not updating with new score in arithmetic assessment

For a school project, I am working on creating a completely randomized math quiz utilizing HTML, CSS, Javascript, and possibly JQuery. The quiz should involve three different operators and must also be visually appealing with CSS styling. I've encoun ...

Adding a library (typings) to a standalone instance of Monaco Editor: Step-by-step guide

My editor setup includes the following: editor.create(this._element, { language: "javascript", minimap: { enabled: false }, automaticLayout: true, readOnly: this.props.readOnly, }); In orde ...

Remove the "hover effect" from an element using programming on mobile devices

There is an element on my webpage that has a specific set of styles for when it is hovered over. However, on mobile devices, this triggers the "sticky hover" effect, where touching the element applies the hover effect until the user touches another part of ...

"Exploring the dynamic trio of Ajax, JavaScript

Seeking assistance with passing a variable between PHP and JavaScript in my code. I have two PHP files - one for viewing and the other for processing, along with a JavaScript file for handling ajax requests. Review of my global.js file: window.onload ...

Is it possible to use $.post and $.get to update the title without changing the logging functionality?

Here is a portion of my code where I am posting to a link. The issue I am facing is that it allows me to change the title, but for some reason, it does not call the function info() with the argument provided. Additionally, it does not log anything in the c ...

Using Selenium to Retrieve HTML Content Between Two Tags

How can I extract the following data from the provided HTML using Selenium 4 and XPath in Python? Message names (e.g. Message 1), Received timestamp (e.g. Received: 214-2342-234), and the most challenging part: message text (e.g. This is message nr. 1 it ...

Removing a field from a SubDocument using Mongoose

In my current Mongoose setup, I have the following schema and code implementation: Schema: { ... inv: { type: Object, default: {} }, ... } Version 1 of the Code involves targetData as a Mongoose Document, item as a String ...

Unable to fetch data in CakePHP 3.x controller using jQuery AJAX POST

I've been searching everywhere and unfortunately, I can't seem to figure out why the data is not being sent to my controller when posting via ajax. Here's the jQuery code snippet: var newDate = {}; newDate['start' ...

Tips on using dual drop-down menus for sorting options

I am encountering a small issue with my two filters. When I choose the values IN and ENCODE, all the values are displayed correctly... https://i.sstatic.net/Uoido.png However, the problem arises when I click on OUT, as the status is not displayed correc ...

Inserting multiple rows of data into a MySQL database in a single page using only one query in PHP

This snippet shows a MySQL query being used to update and insert data into a database: if ($_POST["ok"] == "OK") { $updateSQL = sprintf("UPDATE attend SET at_status=%s, at_remarks=%s WHERE at_tt_idx=%s", GetSQLValueString ...

Guide to displaying a tooltip based on certain conditions using Vue.js

I am working on conditionally displaying a tooltip using v-tooltip based on a Boolean value. This is the current code snippet I have: <div v-for="predefinedContentItem in getPredefinedContentCategoryItems(category.id)" :class="['category-item-c ...

Access the current theme colors of Bootstrap using JavaScript

My goal is to generate charts with chart.js using colors that align with the chosen Bootstrap 4 theme (which has several options available for the site). My approach at the moment involves having a badge of each color displayed on the page: <div id= ...

Incorporating Nunjucks into an Express Application

My Node app previously used Swig as the view engine, but since it's been deprecated, I'm attempting to switch over to Nunjucks. However, after configuring Nunjucks according to the documentation, I am running into runtime errors when trying to lo ...