Altering an element's visibility from 'none' will trigger its animation to play once again

Take a look at the snippet below and you'll see that the sliding animation plays twice - once when the .addClass statement runs, and again when #test's display is switched to 'initial' (timeouts are in place to help visualize the issue):

$(() => {
  $('#test').addClass('animate');

  setTimeout(() => {
    $('#test').css({ display: 'none' });
    setTimeout(() => {
      $('#test').css({ display: 'initial' });
    }, 1000);
  }, 1000);
});
#test {
  position: relative;
  left: 0;
}

#test.animate {
  animation: move 1s ease forwards;
}

@keyframes move {
  100% {
    left: 100px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="test" src="https://cdn4.buysellads.net/uu/1/3332/1524843316-62666.png">

What causes an element's animation to replay when changing its display attribute from 'none' to a visible state ('initial', 'block', etc.) using JavaScript, and how can this be prevented?

Note: setting animation-fill-mode to 'forwards' is a requirement.

Answer №1

To stop the animation after the initial movement, simply remove the animate class.

$(() => {
  $('#test').addClass('animate');

  setTimeout(() => {
    $('#test').addClass('pause').css({ display: 'none' });
    setTimeout(() => {
      $('#test').css({ display: 'initial' });
    }, 1000);
  }, 1000);
});
#test {
  visibility: hidden;
  position: relative;
  left: 0;
}

#test.animate {
  visibility: visible;
  animation: move 1s ease forwards;
}

#test.animate.pause {
  animation-play-state: paused;
}

@keyframes move {
  0% {
    display: none;
    left: 100px;
  }
  1% {
    display: inital;
    left: 0px;
  }
  100% {
    left: 100px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="test" src="https://cdn4.buysellads.net/uu/1/3332/1524843316-62666.png">

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

Tips for creating a customized dropdown menu that opens upwards without relying on Bootstrap

Looking for some assistance with creating an animated dropdown menu that slides upwards. Any help is appreciated! $('.need-help').click(function() { $('.need_help_dropdown').slideToggle(); }); .need-help { background:url(../im ...

Is there a way to disable a dropdown menu when clicking on a different one?

[![ Dashboard Admin Admin Profile Change Password Doctors Doctors List Doctors Appointments Doctors Requests Add a Doctor Patients ...

finding and retrieving every occurrence of the select directive and its corresponding selected values in Angular

I recently set up a chosen dropdown in my project using the following method. I added a select box with a "chosen" directive as an attribute to update and initialize a list, along with an ng-model on the select element. <select id="{{$index+1}}" class= ...

Content within a Row of a Data Table

Hello! I am just starting to learn JavaScript and jQuery. Can you help me with an issue I am experiencing? Basically, I have a table and I need to identify which tr contains a td with the text "Weekly", "Daily", or "Monthly". Once I locate that specific t ...

Tips for displaying user data from a mongodb database on a webpage, making edits to the information, and then saving the updated data

I have a website where users can register, log in, and update their profile information. However, I am facing an issue where only the data of the first user in the database table is being retrieved. How can I get the data of the currently logged-in user? ...

What are the alternative ways to deploy a React app on Node.js without relying on Express?

Is there a way to achieve serving html files without using Express in Nodejs? I have experience with serving html files through http/https in a typical website without a frontend framework, but when attempting to do the same with index.html from a React ap ...

Once I incorporated Bootstrap into my project, I noticed a noticeable white space between the div elements

Welcome to My Code Playground I was sailing smoothly with my project until I decided to include Bootstrap. Seems like there's something missing in the details, so here I am reaching out. If you spot the issue, please feel free to correct my code. &l ...

Disabling directional focus navigation in CSS: A comprehensive guide

Is there a way to disable directional focus navigation properties, such as 'nav-up', 'nav-right', 'nav-down', 'nav-left', for elements on an HTML page? button { position:absolute } button#b1 { top:0; left:50%; ...

Obtain the final output of a specific class utilizing jQuery

My HTML table structure is as follows: <tbody id="letter-list"> <?php $index = 0; foreach($letters as $letter) { $index++; ?> <tr id="letter-<?php echo $index; ?>"> <td><?php echo $l ...

Placing HTML text on top of a three.js renderer

I have been attempting to overlay HTML text onto my three.js sketch, but adjusting the z-index does not seem to be working. While I know that I could utilize innerHTML, the issue arises when I need to also use the onclick attribute, which is not the main f ...

Looking to transform a list into JSON format using JavaScript?

I have a collection that looks like this: <ol class="BasketballPlayers"> <li id="1">Player: LeBron, TotalPoints: 28753, MVP: true</li> <li id="2">Player: Steph, TotalPoints: 17670, MVP: true< ...

Unable to alter the background color of the text box

I am currently struggling with my code where I am trying to overlay a text box on an image. Even after setting the background color to white, it still shows up as transparent. I have successfully done this in the past, but for some reason, it is not work ...

What methods can be used to pause a jQuery function when hovering and resume it when the mouse leaves?

I'm currently working on a jQuery function that operates on the mousemove event. The goal is to have two images - one main image and one shadow image, with the shadow image reflecting movement based on mouse position. While everything is functioning p ...

Create a custom overlay for an image that is centered horizontally and does not have a fixed width

I'm working with this HTML setup: <div class="container"> <img class="image" /> <div class="overlay"> <div class="insides">more content here</div> </div> &l ...

Are there any images included in the WebResponse being downloaded?

I need to download HTML efficiently in order to parse it with minimal bandwidth consumption. Here is a snippet of my code: if (!String.IsNullOrEmpty(siteAddress)) webReq = WebRequest.Create(siteAddress) WebResponse webRes ...

Error Alert: jQuery Ajax Not Executing

Looking to send form data to PHP using jQuery. Check out the code below. -------------HTML FORM-------------- <div id="createQuestionBlock"> <form id="createQuestionForm" action="" method="POST"> Question Code: <input id="code" ...

Getting rid of the Horizontal Scroll Bar

Having trouble with a persistent horizontal scrollbar in the "section3__container" container despite attempts to adjust size and overflow settings. Need assistance in removing this unwanted feature. <html lang="en"> <head> <m ...

Footer refusing to stay fixed at the bottom of the viewport

Currently, I am utilizing fullpage.js with scrolloverflow.js activated on the second section. In this setup, I would like to have a footer that remains fixed at the bottom of the viewport for the second section only. However, instead of achieving this desi ...

Ways to retrieve the innerHTML of a Script Tag

After spending what feels like an eternity searching, I still can't figure out how to get the innerHTML of a script tag. Here's where I'm at... <script type="text/javascript" src="http://www.google.com" id="externalScript"></script ...

Outputting PHP code as plain text with jQuery

My aim is to set up a preview HTML section where I am encountering a difficulty. I am struggling to display PHP code when retrieving and printing it from a textarea in the HTML. Here are my current codes, This is the HTML area where the textarea code will ...