Animate a DIV to the bottom of the page, then with another click, animate it back to the top

I've been working on a div animation where the original position of the div from the top is set at 70% and the div itself is set as absolute. However, when I click on a button, it slides to the bottom of the page with a top value of 95%.

Now, my goal is to check if the position has reached top:95%, and if so, slide it back to top:70%.

For some reason, the div slides down to 95%, but doesn't come back up. What am I doing wrong here?

CSS:

#mainMenu {
    width: 100%;
    height: 30px;
    background-color: black;
    top: 70%;
    position: absolute;
}

body {
    margin: 0px;
}

#clickToCheck {
    font-size: 22px;
}

JQuery:

<script>
$(document).ready(function () {

    $('#mainMenu').click(function () {

        $("#mainMenu").animate({ top: "95%" }, 1100);

    });
});


$(document).ready(function () {
    $('#clickToCheck').click(function () {
        if ($('#mainMenu').position().top === '95%') {
            $("#mainMenu").delay(1000).animate({ top: "70%" }, 1200);
        } else {
            alert('It's not at the bottom');
        }
    });
});

HTML:

<body>
<span id="clickToCheck">Click to Check</span>
<div id="mainMenu"></div>

Answer №1

One issue to be aware of is that the function

$('#mainMenu').position().top

Returns the value in pixels instead of percentage. If you need to determine if the top is at 95%, you'll have to calculate this based on the top position and either the window height or the div's height. Here is a sample code snippet:

$('#mainMenu').position().top/$(window).height()*100

This will give you the percentage of #mainMenu relative to the entire window. If #mainMenu is within a div, adjust it according to the div's height. Keep in mind that you may receive a decimal number like 94.2343123. Therefore, when checking the percentage, consider using something like "if >= 93" rather than an exact match like "if = 95".

Answer №2

An issue arises with the default behavior of .position(), .offset(), and .css() as they all operate in pixels.

To address this, a practical solution would involve saving the original .offset() of the menu using .data() and evaluating if there has been any change in its offset.

See Demo

$(document).ready(function () {
    $('#mainMenu').data('startPos', $('#mainMenu').offset().top); // store original offset top on document ready
    $('#mainMenu').click(function () {

        $("#mainMenu").animate({
            top: "95%"
        }, 1100);
    });

    $('#clickToCheck').click(function () {
        if ($('#mainMenu').offset().top > $('#mainMenu').data('startPos')) { // check if new offset is greater than original offset 
            $("#mainMenu").delay(1000).animate({
                top: '70%'
            }, 1200);
        } else {
            alert('it is not at the bottom');
        }
    });
});

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

Execute script when on a specific webpage AND navigating away from another specific webpage

I created a CSS code that adds a fade-in effect to the title of my website, and it works perfectly. However, I now want to customize the fade-in and fade-out effect based on the page I am transitioning from. My desired outcome: If I am leaving the "Biolo ...

Learn the steps to invoke a JavaScript function from a <td> element within an ng-repeat loop

How can I call an Angular function inside ng-repeat td and replace the value from the function with the value in the td element? The code snippet provided below is not functioning as expected. Instead of getting the date, the same getCSTDateTime function i ...

AngularJS loads the index into the ui-view using UI-router

While working on a site using AngularJS, everything appears to be working perfectly when run locally. However, in the deployed version, there is a strange issue where 'index.html' is being loaded in the ui-view instead of the specified partial at ...

Using JQuery's getJSON() method causes the URL in the request header to be duplicated

I have encountered an issue with a duplicated value in the request URL while attempting to execute the following AJAX function: var url = "localhost/travel/home/getPrevApplicantData"; $.getJSON(url, {group_id : "1"}) .done(function(data) { console.log ...

An issue arises when attempting to utilize the 'push()' method to append a string to a JSON array

I am looking to append strings to my JSON file structure shown below: { "items": [] } To achieve this, I have the requirement of using the following code: var items = require("../../config/item.json"); The approach I am taking is ...

React Router 4 - Optimizing Component Refresh by Remounting Instead of Re-Rendering

I am currently in the process of configuring a React project that utilizes React Router 4 ("react-router-dom": "^4.3.1"). Within this project, I have implemented a SideBar, a NavBar, and the main content section of the application which changes based on th ...

Can someone provide a method to access the namespace of an Angular controller when utilizing the "Controller As" format?

Imagine you have an AngularJS ngController directive set up like this: <div ng-controller="SomeCtrl as herpderp">…</div> Is there a way to extract the namespace ("herpderp") from within the SomeCtrl controller itself? This could be useful f ...

What is the significance of the error message "Uncaught (in promise) Object"?

I am facing an error in my code and need help to correct and debug it. I would like the code execution to halt when an issue arises. Here is my code snippet: export function postRequestOtpCode(phone: string, token: string): CancellableAxiosPromise { ax ...

The script was denied execution due to the non-executable MIME type ('text/html') and the activation of strict MIME type checking

I'm currently attempting to retrieve data from the forismatic API, but I'm not receiving any response. I'm using AJAX in jQuery, however, I keep encountering the following error in my console: The script at '' was refused to execu ...

The function is not defined... HOWEVER... it functions perfectly in a separate demo file

I have been attempting to implement a similar effect found here: . It's a responsive popup that can display content on demand. Initially, I have jquery 2.0.2 and jquery-ui included in my <head> section, which are loading successfully. Then ...

After refreshing the page, Angular 8 may incorrectly load JavaScript from an incorrect path when accessing a lazy loaded

Whenever I refresh the page while on a lazy loaded module, the application breaks because it attempts to import JavaScript files from an incorrect path. Here is an overview of my routing configuration: App Routing Module: { path: 'accommodations&ap ...

The main page wrapper will be centered on all devices except for tablets, where it will appear

I have set up a main container, #main, for my page content with a central position. It is positioned absolutely to create some space above the container. Centering is achieved using negative margins and left:50% instead of margin:auto. However, the issue a ...

Convert HTML form input into a JSON file for safekeeping

<div class="email"> <section class="subscribe"> <div class="subscribe-pitch"> </div> <form action="#" method="post" class="subscribe-form" id="emails_form"> <input type="email" class="subscribe-input" placeholder="Enter ema ...

What makes Next.js API so special?

As I delve into Next.js, I find myself grappling with the concept of server-side rendering (SSR) and API usage. When is it appropriate to utilize the API folder within pages versus deploying my own server along with a database? Would there be any conflic ...

The Ajax post feature in a WordPress plugin is failing to return any data, resulting

Does anyone have a moment to take a look at this abandoned WordPress plugin file that seems to be causing some trouble? The Ajax post data is returning an empty array, leading to script errors. It appears that something in WordPress may have changed, causi ...

Ajax fails to transmit information

Currently, I am in the process of familiarizing myself with the usage of ajax. An issue that I am encountering is that clicking a submit button in a form does not effectively send data. Below you can find the JQuery code I am using: $('input[name=" ...

Tips for simulating an axios request that returns an image buffer

I am attempting to simulate an axios api call that returns an image buffer as shown below: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e1 00 de 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 06 00 12 01 03 00 01 00 00 00 01 00 ... ...

Unexplained code snippet: templates.keys() iterating over templates in Webpack - what does it signify?

I'm exploring ways to include html templates in a Webpack bundle using ngTemplate-loader and html-template-loader. While examining code from another project, I came across two lines that achieve this: const templates = require.context(__dirname, true ...

Best practices for server side countdown implementation

Issue I am facing a challenge with displaying a server-side countdown on the client side. Initially, I set it up using socket.io to emit data every 100 milliseconds. While I like this approach, I am concerned about potential performance issues. On the o ...

What are some effective methods for analyzing a minified JavaScript file within Visual Studio?

There have been numerous instances where I've received minified javascript and css files to be used in html. In similar situations in .Net, I utilize the Object Browser in Visual Studio to easily view all methods and properties along with comments, ma ...