Animating object on display and returning it with keyframes

Given the code snippet below:

<div class="leftBox">
    <div class="mainNode" ></div>
</div>
<script type="text/javascript">
$('.mainNode').click(function() {
    var element = $('.mainNode');
    if (!element.hasClass('show')) {
        element.removeClass('hide');
        element.addClass('show');
    } else {
        element.removeClass('show');
        element.addClass('hide');
    }
})
</script>

In the CSS:

.mainNode {
    width: 160px;
    height: 160px;

    border-radius: 50%;
    background-color: red;
    position :relative;
}

.show {
    -webkit-animation: mymove 1s forwards; /* Safari 4.0 - 8.0 */
    animation: mymove 1s forwards;
}

.hide {
    -webkit-animation: mymove 1s reverse; /* Safari 4.0 - 8.0 */
    animation: mymove 1s reverse;
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes mymove {
    from   {top: 0px;}
    to {top: 200px;}
}

/* Standard syntax */
@keyframes mymove {
    from   {top: 0px;}
    to {top: 200px;}
}

I want the circle in the code to move to the bottom when clicked using keyframes.

Once clicked, it should stay at the bottom, which is working as expected with the current code provided.

However, upon clicking again, I would like the circle to animate back to its original position and be able to repeat this action of moving up and down smoothly. Currently, this behavior is not functioning correctly, as the circle jumps abruptly instead of animating.

Any assistance on fixing this issue would be greatly appreciated.

Here's an example of the code

Answer №1

Give this a shot. I've put my best effort into it. The animation moves from top to bottom and then back from bottom to top every time.

$('.mainNode').click(function() {
    var element = $('.mainNode');   
    
    if (!element.hasClass('show')) {
        element.removeClass('hide');        
        element.addClass('show'); 
        element.before( element.clone(true)).remove();
    } else {
        element.removeClass('show');        
        element.addClass('hide');
         element.before( element.clone(true)).remove();
    }    
})
.mainNode {
  width: 160px;
  height: 160px;
  border-radius: 50%;
  background-color: red;
  position :relative;
}

.show {
  -webkit-animation: mymove 1s forwards; /* Safari 4.0 - 8.0 */
  animation: mymove 1s forwards;  
}

.hide {
  -webkit-animation: mymove1 1s forwards; /* Safari 4.0 - 8.0 */
  animation: mymove1 1s forwards;  
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes mymove {
  from   {top: 0px;}
  to {top: 200px;}
}

/* Standard syntax */
@keyframes mymove {
  from   {top: 0px;}
  to {top: 200px;}
}
/* Safari 4.0 - 8.0 */
@-webkit-keyframes mymove1 {
  from   {top: 200px;}
  to {top: 0px;}
}

/* Standard syntax */
@keyframes mymove1 {
  from   {top: 200px;}
  to {top: 0px;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="leftBox">
    <div class="mainNode"></div>
</div>

Answer №2

Instead of using the reverse function, try using backwords for better results.

.hide {
    -webkit-animation: mymove 1s backwords; /* Safari 4.0 - 8.0 */
    animation: mymove 1s backwords;
    animation-delay: .2s;
}

Answer №3

You must adjust two settings to ensure proper functionality:

.hide {
    -webkit-animation: mymove 1s reverse forwards; /* Compatible with Safari versions 4.0 - 8.0 */
    animation: mymove 1s reverse forwards;
    animation-delay: .2s;
}

Utilize animation-direction: reverse, but set animation-fill-mode: forwards. By doing this, the animation will initiate from the end and persist at the final keyframe (returning to the starting point).

However, there is an additional issue: Upon removal of the show class, the element abruptly snaps back to its initial state as the animation ceases. To resolve this, you can include animation-name: mymove within your .mainNode CSS segment.

.mainNode {
    animation-name: mymove;
    // Other properties...
}

Observe the changes in action via the following link: https://codepen.io/anon/pen/jLgrjW

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

Preventing undesired form submissions in HTML and JavaScript

My question might be simple, but it's what I have in mind. When working with two buttons in HTML - one for form submission and the other to trigger a JavaScript event - both buttons end up submitting the form. How can I make sure the second button onl ...

Using JavaScript to generate JSON data in a plain text format rather than using HTML

I have a snippet of code that retrieves the user's location every 5 seconds. <div id="geo" onLoad=""></div> <script> function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPo ...

What is the best way to send an HTTP request in AngularJS to receive data in JSON format?

I am trying to create an AngularJS app that can send HTTP requests for JSON data. I have written the code in my index.html file to request JSON data using AngularJS, but for some reason, the JSON data is not being printed. When I check the console in Fire ...

Positioning elements in a header using CSS techniques

I am currently working on designing a navigation menu header that includes a logo, along with some buttons aligned to the left side of the logo. However, I am facing an issue where these buttons appear at the bottom of the logo instead of aligning to the t ...

Executing a function in Node-Express with a database connection at the beginning of the application

I am relatively new to Node.js and currently working on a Node.js - Express solution as a back-end for an AngularJS web application. My goal is to send an email when the MSSQL database query returns specific information. I have successfully implemented thi ...

What is the best way to detect if a user has reached the end of a container div while implementing Infinite Scroll

I am in the process of implementing infinite scroll on our website's dashboard, but I am currently facing a challenge in determining the bottom of the container div in my jsfiddle mockup. The original function works on a blank page with no container ...

Guide for displaying and hiding an image using a button or link in Next.js

I'm a beginner with React and Next.js, and I have the following code snippet: import Link from 'next/link'; import Image from 'next/image'; async function getPokedex() { const response = await fetch(`http://localhost:3000/api/p ...

Issues with the initial drop functionality in jQuery UI

How come the jQuery code does not work properly on the first drop? $(".drag").draggable({ revert: 'invalid', drag: function(event, ui) { $(this).addClass('valid'); } }); $("#droppable").droppable({ accept: '.valid&apos ...

Having trouble displaying specific images on React Native, how can I resolve this issue?

I am currently developing a weather application that retrieves weather information and displays it using ForecastItem components. However, I have noticed that some of the components do not display the weather image randomly. On the Home screen, I use the ...

The absence of a type annotation for `T` has been noted

Attempting to create code with a simple JavaScript function: filterArray(user: any, items: Array<Object>) { items = items.filter(item => {return true;}); return items; } Encountering the following error: Error message: Missing type anno ...

Guide to changing the class of a particular child element when the parent element is clicked with vanilla JavaScript

Upon clicking the parent button, a class within its child element will toggle to show or hide. If the child element is selected, a loading animation will appear for a brief moment before reverting back to its original hidden state. I attempted to achieve ...

What is the best method to keep content confined within a box inside the grid, while also allowing the box to extend beyond the grid boundaries?

Apologies for the confusing title, but I must confess that I am unsure if there are more appropriate terms to explain what I am attempting to achieve. To provide clarity, I have included an image (as they say, a picture is worth a thousand words) https:// ...

Balancing website speed with capturing product impression

I've been tasked with capturing impressions of all the products visible in the viewport on a website that features thousands of products. To achieve this, I implemented a directory and utilized the IntersectionObserver, which was referenced within the ...

New issue with installing npm cra

Recently updated to npm version 6.14.4 and encountered an issue while trying to create a new app with cra-template. How can I resolve this problem? npx create-react-app sphinx.ui.react Error Log 50 timing stage:runTopLevelLifecycles Completed in 5234ms ...

Show the Table and Conceal the Overflow

Currently, I am experimenting with creating an Img hover for entertainment purposes. However, I have added some text to my div. In order to center the text beautifully within my div, I utilized the following CSS code: display: table-cell; vertical-align: ...

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

Exploring new possibilities in ChartJS with the use of multiple Y

I have successfully created a line chart using Chart.js with two datasets, each having its own Y scale and axis. The code for my datasets and options is as follows: datasets: [{ fill:false, label: 'Heat', yAxisID: "y-axis-1", da ...

Using the input type 'number' will result in null values instead of characters

My goal is to validate a number input field using Angular2: <input type="number" class="form-control" name="foo" id="foo" [min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo"> In Chrome, everything works perfectly because it ignores ...

Having trouble with Vue.js not returning HTML elements from methods properly?

I have been attempting to retrieve html elements from a method, and I thought of using v-html for this purpose (not sure if there is a better approach). However, I seem to have encountered an issue with backtick templates and string interpolation. An error ...

The jQuery bookmarklet in the djangobyexample book is completely unresponsive

As I work my way through Django By Example, I came across a chapter where a jQuery bookmarklet is created within a Django app. This allows users to easily save jpg images from websites into their user profile area within the Django app. Although the tutor ...