What is the best way to reset an animation back to its original state after clicking the button again?

Forgive my lack of understanding, but I can't seem to figure this out. I have a navigation bar centered both horizontally and vertically with a button inside. When the button is clicked, the nav bar animates to the top of the page with a slight margin remaining. What I'm attempting to accomplish is for the nav bar to return to its original position when the button is clicked again. Despite trying multiple lines of code, I've been unsuccessful in achieving this (which shouldn't be overly complicated). Any assistance would be greatly appreciated.

JavaScript:

$("#btn").click( function(event){
    $("#wrapper").animate({
        'top': 100
    }, 400) 
});

CSS:

#wrapper {
    position:absolute;
    top:50%;
    margin-top:-100px;
    left:0;
    width:100%;
}

#nav {
    margin:20px auto;
    height:200px;
    width:900px;
    text-align:center;
    background-color:#bca;
    border:1px solid green;
}

JSFiddle available here.

Answer №1

If you're looking for a solution, this might work:

Check out the DEMO on jsFiddle

$("#btn").on('click', function(event){
    this.isToggled = !this.isToggled;
    $("#wrapper").stop().animate({
        'top': this.isToggled ? 100 : "50%"
    }, 400)
});

Answer №2

To create a toggle effect, you can use a variable like clicked to keep track of whether the element has been clicked or not. On the first click, the element moves up, on the second click, it moves back down, and so forth.

JSFIDDLE LINK

var clicked = false;
$("#btn").click(function(event) {
    clicked = !clicked;
    if (clicked) {
        $("#wrapper").animate({
            'top': '-=100'
        }, 400)
    } else {
        $("#wrapper").animate({
            'top': '+=100'
        }, 400)
    }
});

Answer №3

If you want to accomplish this task, consider utilizing the switchClass plugin from jquery UI. Alternatively, you can achieve it in a less elegant manner by making adjustments to your code:

$("#btn").click( function(event) {
    var top = $("#wrapper").css('top') == '100px' ? '50%' : 100;
     $("#wrapper").animate({
        'top': top
      }, 400)
});

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 response from Moment.js shows the date as "December 31, 1969."

Currently, I am in the process of recreating one of FCC's backend projects: Upon testing my code, I noticed that when I input the following URL: http://localhost:3000/1 The result is as follows: {"unix":"1","natural":"December 31, 1969"} var e ...

Updates to Bootstrap 4 Navbar

I have some simple CSS questions that are giving me a bit of trouble; How can I make the green background take up the full height of the navbar on hover for a nav-item? Also, how can I center the nav-item text and add a border-bottom when the navbar is c ...

Inject the type into the dependency container

I am managing multiple databases without relying on ORM tools. Here, I will demonstrate an example using Postgres and MSSQL databases with UserQueries. https://i.sstatic.net/GFs5D.png Within my codebase, I have an interface called IDataBase which is impl ...

Transferring binary fragments to Node.js for assembly into a complete file. Creating a file

Hey there, I'm in a bit of a bind. I'm trying to send file chunks using multiple XMLHttpRequest requests and then receive these parts in Node.js to reconstruct the original file from the binary data. The issue I'm facing is that the final f ...

Struggling to get moment().utc() to display a two-digit format for the month and year

Currently, I am tackling a bug that has surfaced in a birthday component within my application. This component pulls the date of birth from its props in the format 1997-08-16T00:00:00Z. The challenge I am facing is that when the date of birth is set in the ...

Utilize cloning feature instead of moving elements in JQuery UI and AngularJS

At the moment, I am actively involved in a project using angular Js. My current task involves creating two div elements with drag and drop functionality. If you want to take a look, here is the jsfiddle link. I am seeking a way to make it so that when I ...

The updates made to a variable within an ajax request are not immediately reflected after the request has been completed

My global variable is not displaying the expected result: function checkLiveRdv(salle, jour, dateus, heure) { var resu; var urlaction = myUrl; $.ajax({ type: "POST", dataType: "json", url: urlaction, data: myDatas, suc ...

I am looking to insert a link into each column, but unfortunately, the styling is becoming disrupted whenever I attempt to do so due to the constraints

Is there a way to add links to each column without disrupting the current styling? Apologies for the messy code, I am still new to this field. <div class="row justify-content-end"> <a href="#"><div class=&qu ...

The functionality of Bootstrap Mobile css is most effective when navigating by scrolling downwards

I am experiencing a strange issue. I am using Ajax to load the Search form. The CSS is being applied correctly, but there is an unusual problem with the bottom margin. The bottom margin only appears when you scroll down in mobile view. When you load the f ...

What is the best way to convert my Chatbot component into a <script> tag for seamless integration into any website using React.js?

I have successfully integrated a Chatbot component into my Next.js application. https://i.stack.imgur.com/BxgWV.png Now, I want to make this component available for anyone to use on their own website by simply adding a tag. My initial approach was to cre ...

Choosing classes with BEM convention

I've been working on implementing the BEM naming convention, and I'm facing a challenge with styling a "tooltip" block using different themes. For example, applying the "default" theme like this: <div class="tooltip tooltip_theme_default"> ...

Switch the measurement unit in the .dotdotdot script from pixels to percentages for the height value

I'm looking to convert the height value from 100 pixels to a percentage, specifically 50%. I have limited experience with javascript... <script language="javascript" type="text/javascript"> $(document).ready(function(){ $(".item-info-overla ...

Tips for transforming a date into a time ago representation

Can someone help me with converting a date field into a "timeago" format using jquery.timeago.js? $("time.timeago").timeago(); var userSpan = document.createElement("span"); userSpan.setAttribute("class", "text-muted"); userSpan.appendChild(document.crea ...

Leveraging Node.js socket.io alongside React's web worker for streamlined communication

I have a project that involves using socket.io, React.js, and Webworkers https://i.sstatic.net/3SUg3.png Components A and B are child components of the Home page component. These components also function as tabs, so when A is mounted, B is unmounted, and ...

Changing the entire contents of an array through innerHTML manipulation

I've encountered a strange issue with my Javascript code. I'm trying to create a table row using document.createElement("tr") and an array of cells like this: cell = new Array(3).fill(document.createElement("td")); However, when I populate the c ...

An erroneous if statement in JavaScript is being triggered

I have a series of if statements that output different strings from corresponding lists based on the input (feelsLike). View Code Initially, it identifies the range in which feelsLike falls and then concatenates all items in the list into the string. Whe ...

Is there a way to stream an mp3 file in a Node.js REPL on Replit?

I have an MP3 file that I want to play when a button is clicked. However, I suspect that I am not correctly serving the file to the server. The following code snippet is from my project on Replit.com: const app = require('express')(); const http ...

Close popup after submitting the form

On my website, I have a function to submit a form within a modal. Everything works well except for when I uncomment a certain line of code. When I uncomment that line, my test mysql insert on the page /index.php/trainings/add doesn't get executed. I a ...

Adjust the month to be plotted on the X-axis of the ColumnChart using the specified

My ORIGINAL POST: I've put together a fiddle to showcase how my data is sourced from JSON and displayed in a ColumnChart. https://jsfiddle.net/w4dokdt9/3/ This is an example of how my JSON data is structured: [{"lPlusScoreID":1,"jan":60.03,"feb":4 ...

Organizing items by a string attribute in TypeScript

My data consists of an array of objects with a structure similar to this: export class AccountInfo { accountUid: string; userType: string; firstName: string; middleName: string; lastName: string; } NOTE: I opted not to use an enum for userType ...