Guide to resetting a CSS animation with pure JavaScript

My flexbox contains 4 images, each triggering an animation on hover. However, the animation stops if I hover over the same image again.

I have tried various JavaScript solutions found online to restart the animation, but none seem to be working for me.

Should I target the span by its ID and add/remove the "textAnim" class using JavaScript? And how can this be done when hovering over the image?

/* Images Section Styling */

.container-3 {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  position: relative;
}

.container-3 img {
  max-width: 100%;
  max-height: 100%;
}

.image {
  position: relative;
  max-width: 100%;
  max-height: 100%;
}


/* Image overlay */

.overlay {
  position: absolute;
  display: flex;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  color: rgba(255, 255, 255, 0);
  background-color: rgba(107, 105, 105, 0);
  transition: background-color 1s ease;
  transition: color 1s ease;
  overflow: hidden;
}

.image:hover .overlay {
  background-color: rgba(107, 105, 105, 0.5);
  color: rgba(255, 255, 255, 1);
  transition: background-color 1s ease;
}

.textAnim {
  animation: textAnimation 1s;
  animation-play-state: paused;
  position: relative;
  padding-left: 50%;
  top: 50%;
}

.image:hover .textAnim {
  animation-play-state: running;
}

@keyframes textAnimation {
  0% {
    opacity: 0;
    padding-top: 50%;
  }
  100% {
    opacity: 1;
    padding-top: 0%;
  }
}
<section class="images">
  <div class="container-3">
    <div class="image">
      <img src="http://via.placeholder.com/1000">
      <div class="overlay">
        <span class="textAnim" id="animation">
                            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum, enim?
                        </span>
      </div>
    </div>
    <div class="image">
      <img src="http://via.placeholder.com/1000">
      <div class="overlay">
        <span class="textAnim" id="animaiton">
                            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum, enim?
                        </span>
      </div>
    </div>
    <div class="image">
      <img src="http://via.placeholder.com/1000">
      <div class="overlay">
        <span class="textAnim" id="animation">
                            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum, enim?
                        </span>
      </div>
    </div>
    <div class="image">
      <img src="http://via.placeholder.com/1000">
      <div class="overlay">
        <span class="textAnim" id="animation">
                            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum, enim?
                        </span>
      </div>
    </div>
  </div>
</section>

Answer №1

There is no need to rely on JavaScript to restart the animation in this scenario.

The simple change mentioned below will ensure that the animation continues each time you hover over the image.

.image:hover .textAnim {
  animation-play-state: running;
}

If you maintain the animation to run solely on hover, you will achieve the desired outcome.

Here is the updated code snippet -

/* Styling for Images Section */

.container-3 {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  position: relative;
}

.container-3 img {
  max-width: 100%;
  max-height: 100%;
}

.image {
  position: relative;
  max-width: 100%;
  max-height: 100%;
}


/* Image overlay */

.overlay {
  position: absolute;
  display: flex;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  color: rgba(255, 255, 255, 0);
  background-color: rgba(107, 105, 105, 0);
  transition: background-color 1s ease;
  transition: color 1s ease;
  overflow: hidden;
}

.image:hover .overlay {
  background-color: rgba(107, 105, 105, 0.5);
  color: rgba(255, 255, 255, 1);
  transition: background-color 1s ease;
}

.image:hover .textAnim {
  animation: textAnimation 1s;
  animation-play-state: paused;
  position: relative;
  padding-left: 50%;
  top: 50%;
}

.image:hover .textAnim {
  animation-play-state: running;
}

@keyframes textAnimation {
  0% {
    opacity: 0;
    padding-top: 50%;
  }
  100% {
    opacity: 1;
    padding-top: 0%;
  }
}
<section class="images">
  <div class="container-3">
    <div class="image">
      <img src="http://via.placeholder.com/1000">
      <div class="overlay">
        <span class="textAnim" id="animation">
                            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum, enim?
                        </span>
      </div>
    </div>
    <div class="image">
      <img src="http://via.placeholder.com/1000">
      <div class="overlay">
        <span class="textAnim" id="animaiton">
                            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum, enim?
                        </span>
      </div>
    </div>
    <div class="image">
      <img src="http://via.placeholder.com/1000">
      <div class="overlay">
        <span class="textAnim" id="animation">
                            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum, enim?
                        </span>
      </div>
    </div>
    <div class="image">
      <img src="http://via.placeholder.com/1000">
      <div class="overlay">
        <span class="textAnim" id="animation">
                            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum, enim?
                        </span>
      </div>
    </div>
  </div>
</section>

Answer №2

 however, upon hovering again, the animation ceases to play

if you desire an infinite animation, this issue can be resolved by:

have you attempted:

animation-iteration-count: number|infinite|initial|inherit;

https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_animation

my apologies for intending to leave a comment but lacking sufficient reputation

Answer №3

To control CSS animations, simply toggle the textAnim class on and off the desired element. This can be achieved using the JavaScript methods provided by classList.

For instance, if your element is named "animation1", you can set up event listeners to add the textAnim class when hovering over it and remove it when not:

let a1 = document.getElementById("animation1");

a1.addEventListener("mouseover", function()
{
    a1.classList.add("textAnim");
});

a1.addEventListener("mouseout", function()
{
    a1.classList.remove("textAnim");
});

Please Note: It seems that multiple elements are using the same ID (id="animation") in your HTML document. This is considered invalid HTML practice. To resolve this, ensure each ID is unique or use a class instead of an ID for shared styling.

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

The functionality of the Firebase Realtime Database has ceased

After successfully developing an app with Firebase's Real-time Database for the past month, I suddenly encountered an issue today. Despite the authentication features working seamlessly, my app is no longer able to retrieve data from Firebase. It&apos ...

Divide the information in the table across several pages for easier printing

I have encountered an architectural challenge with my server-side React app. The app renders charts and tables with page breaks in between to allow a puppeteer instance to print the report for users in another application. The issue I'm facing is mak ...

Modify an HTML table and record any modifications as POST requests using Javascript

As a beginner in JavaScript and HTML, I am open to corrections if I am not following the correct practices. Recently, I delved into editing an HTML form table. {%extends 'base.html'%} {%block content%} <html> <body> <h4> Search ...

The gradual disappearance and reappearance of a table row

I am struggling with making a row fade out when a specific select value is chosen (such as "termination"), and fade in when any other option is selected. The code works perfectly fine when the div ID is placed outside the table, but once I encapsulate it w ...

Transmitting JSON AJAX response to populate location markers on Google Maps

When a button is clicked, an AJAX response is triggered to display JSON data based on a search query. My goal is to take the all_locations variable from the AJAX response and use it to show markers on a Google map. I'm uncertain about how to achieve t ...

The aligning property "justify-content: space around" does not behave as expected on a line and does not provide the desired spacing

Below is the HTML code I am working on: <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta na ...

To make table headers remain stationary as the data scrolls with JavaScript

When using Explorer, I was able to fix the "thead" part of my table while scrolling by using CSS expressions. The following CSS code snippet showcases how it's done: .standardTable thead tr { position: relative; top: expression(offsetParent.scrollTo ...

Significant issue identified with ajax functionality, requiring immediate attention

After executing the code in the console, I expected to see the ajax object with a readyState of 0 (as I aborted the ajax call). However, Chrome is displaying the number 4 in the console instead of 0. This discrepancy is surprising. http://jsfiddle.net/8yC ...

Tips for ensuring that an Ajax request successfully executes when a page loads

I have a question about implementing an AJAX request in my code. Currently, I have the text on the screen updating when a dropdown input is selected using 'onchange'. However, I also want this same behavior to occur on page load, but I am struggl ...

a non-breaking space within a hyperlink

While working on the subnavigation of a website, I encountered an issue with the link Suite «Mont Blanc», which was pulled from the backend. The desired format for this link was:       Suite «Mont Blanc» However, t ...

Align a div vertically in a responsive design layout

How can I get the text inside "grid2" and "section2" to vertically align in the middle? Is this issue related to my HTML or is it a problem with the CSS? Can someone guide me in the right direction? I have searched for similar questions but the answers h ...

Failed Ajax request is caused by an incorrect URL

In my current project using Ajax, I encountered a peculiar issue. The main page, Main.html, is accessible locally at 'http://localhost/Main.html', and it is styled with Bootstrap. Upon loading the page, jQuery verifies the existence of a particu ...

JavaScript's connection to the CSS property visibility seems to be causing some issues

The Javascript code seems to be ignoring the CSS display property, even though it's set in the style sheet. I added a debugger statement and noticed that the display value was empty. I've been staring at this for some time now, so I must be overl ...

While attempting to use $scope.$apply() in Angular, I encountered a bug that

I have set up a specific example in a jsbin: http://jsbin.com/deqerelita/1/ Situation The concept is quite straightforward. You click a button, the controller adds to the model, and the view updates accordingly with a hidden input type="file". After the v ...

What's the best way to add line numbers to source code on an HTML webpage after parsing?

I am currently working with AngularJS and MongoDB. In my MongoDB data, there are some text elements that contain a \n, causing each line to be displayed on a new line based on the occurrence of \n. However, I also want to add line numbers to each ...

Retrieving the selected value from a dropdown using jQuery's `$('#id').val()` may not always provide the desired result

I am having trouble retrieving the selected value from a dropdown menu as it keeps returning either an empty string or undefined results. My HTML code is structured like this: <div class="input-group" style="padding-bottom: 10px;"> <span id= ...

Error encountered using jQuery $.post: TypeError - e.type is not a valid function

I'm currently in the process of developing a feedback script specifically for the ZetaBoards forum software. My approach has been to create a $.post function, but when I attempt to submit the form by clicking the submit button, all I get in return is ...

Leveraging the power of Javascript and Firebase within the Angular framework

When attempting to integrate Firebase with Angular, I encountered an issue where my localhost was not able to function properly with my JavaScript code. The strange thing is that everything works fine when the code is placed directly in the index.html file ...

Masking Aadhaar numbers

I need to find a way to detect when the back button is pressed on an input field. The methods I have tried, e.key and e.which, are returning as undefined in mobile Chrome. How can I make this work? It's functioning properly on desktop. jQuery(funct ...

Having difficulty incorporating external SASS styles into my React.js project

In most of my projects, I follow a similar process for importing SASS styles. First, I create my react app and then install SASS using the command npm install node-sass. Next, I import my SASS file into my app components as shown below: import React from & ...