Animate as you scroll down and as you scroll back up

Trying to animate a set of buttons from a relative position to a fixed position on each scroll by.

HTML

<div class="menu">
    <button class="button"></button>
    <button class="button"></button>
</div>

CSS

.button {
    display: inline-block;
    position: relative;
    margin: 3px;
    height: 56px;
    width: 56px;

    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

.grouped {
    z-index: 1000;
    position: fixed;
    top: 31px;
    right: 20px;
}

JS

var scrollFlag = false;

$(window).scroll(function() {
    var menu = $(".menu"),
        scrollTop = window.scrollTop;

    if(menu.offset().top <= (scrollTop + 50)) {
        if(scrollFlag == false) {
            $(".menu button").each(function() {
                var button = $(this);

                button.addClass("grouped");
            });

            scrollFlag = true;
        }
    } else {
        $("#intro div.menu button").each(function() {
            $(this).removeClass("grouped");
        });

        scrollFlag = false;
    }
});

The current issue is that the buttons simply snap to the fixed position instead of animating smoothly. It seems that they need predefined top/right values for the animation to work properly.

I attempted to fix this by setting the buttons' offsets as their top and left values, but unfortunately, this did not produce the desired result.

Any suggestions?

Answer №1

Have you considered using JQuery's .animate() method?

Here is an example of how you can implement it:

$("#myButton").animate({         
    //You can specify either the distance you want it to move or the final position.
    top: 50px; 
    left: 50px;
}, 500); //The duration of the animation in milliseconds.

Answer №2

I'm not sure if this is a good idea, but let's give it a try

$(window).scroll(function() {
    var menu = $(".menu"),
        scrollTop = $(window).scrollTop();
    if($('.button:nth-child(1)').css('position') !== 'fixed'){
        if(menu.offset().top <= (scrollTop + 50)) {
            $(".menu button").each(function() {
                var button = $(this);

                button.addClass("grouped");
            });
        }
    } else {
        if(scrollTop  <= 31){
            $("div.menu button").each(function() {
                $(this).removeClass("grouped");
            });
        }
    }
});

Check out the JSFIDDLE link for more details

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

Utilize CSS to selectively target specific sections of a repetitive pattern within a list

I have come across a list fragment that is generated automatically and I only have the ability to adjust the CSS for it. <ul class="menu"> <li class=" menuItem1 first parent"></li> <li class=" menuItem2 parent"></li> ...

When I implemented snap.js on my main content wrapper, I noticed that it was causing a disruption in a few of my jQuery functions

Currently, I am utilizing snap.js to allow the sliding of the main content div using css3 and javascript, exposing a menu beneath. However, I am encountering an issue when I apply the class snap-content to specify which div snap.js should slide - which is ...

Peruse the written content and implement it within a div element

If any of the words match, I want to highlight them in a different color on the website for the user to see. var main = document.getElementById("selectedItem").innerText; var opinionTargets = ["screen", "cover", "size", "waterproof", "voice", "light", "pr ...

jQuery: Issue with controller function execution when using ajax

Currently, I am working on developing a web application using C# MVC that dynamically fetches information from a server to enhance performance. However, I have encountered some errors and I am having trouble pinpointing the exact cause. Allow me to provid ...

implement a click event handler for GLmol (webGL)

Check out GLmol, a Molecular Viewer built on WebGL and Javascript by visiting You can see a demo of GLmol in action at I am interested in adding a click function to GLmol. For example, when I click on a ball, I would like to retrieve information about it ...

Can a webpage have a fixed focus point that automatically adjusts the scroll bar when the content changes?

Looking for some assistance with a message board issue I am facing. As new messages are added, the board constantly expands and pushes older ones down. Is there a way to lock the scroll to a specific message? For example, keeping the same view of message ...

Is incorporating CSS advisable in Karma Unit level tests for AngularJS projects?

Imagine your JavaScript code is running some element or position calculations within an AngularJS directive. When testing this JavaScript code, should CSS be included in karma.conf.js? I've noticed that some popular projects have included CSS files. ...

Issue with offset calculation in bootstrap table occurs when the bootstrap-table is closed and the window is resized

In a recent project, I utilized the bootstrap table. However, upon closing the bootstrap table with the following script: $(document).ready(function () { $(".removetable").click(function (e) { $(".table-aria").remove(); ...

Obtaining serverTime from a webpageWould you like to learn

Is it possible to retrieve the serverTime using jquery ajax functions like $.get() or $.post()? I am looking to store this serverTime in a variable that can be utilized later on in javascript. You can access the webpage at: To use the get and post functi ...

What is the best way to retain selection while clicking on another item using jQuery?

There is a specific issue I am facing with text selection on the page. When I apply this code snippet, the selected text does not get de-selected even after clicking .container: jQuery('.container').on("mousedown", function(){ jQuery('. ...

Horizontal navigation bar encroaching on slideshow graphics

I'm encountering difficulties aligning the horizontal menu below the image slider. When I have just an image without the slider, the menu aligns properly (vertically), but as soon as I introduce the code for the slider, the menu moves to the top and d ...

"Bootstrap 4 does not allow labels to be displayed inline with the input field

I'm currently working with Bootstrap 4 and Vue.js to populate an input form, but I'm struggling to get the label to appear inline and before the input type file. <div v-for="problem in problems"> <div class="row"& ...

Dealing with vast amounts of data through jQuery ajax operations

Currently working on setting up a blog using asp.net, and I am seeking to utilize jquery for adding and displaying posts. However, I have concerns about whether it will function properly when dealing with large amounts of data. In the past, I encountered d ...

Automatic parsing and formatting of JSON object keys

My form is populated automatically using a script. Whenever the user selects an option from a dropdown, an AJAX request is triggered to an external file (which retrieves data from a database using json_encode) and populates the form fields. Here is the sn ...

The presence of a .js file is causing a blockage in the loading

As a beginner in the world of jquery/web design, I decided to download a template to experiment and get more familiar with it. Unfortunately, I encountered an issue with a specific script that is causing my jQuery to not load properly. Here is the snippet ...

Steps to create a hover effect that alters the appearance of another chosen "element"

For instance, I have two classes named A and B. I want to be able to change the appearance of B when I hover over it, such as its color or size. I am unsure if this can be achieved using CSS and the onmouseover event. I am including a snippet of code that ...

Difficulty encountered when trying to display multiple 3D models utilizing a URL as the source in conjunction with ar.js and A-frame

Recently delving into coding for A-frame projects has been an exciting learning experience. However, I encountered a setback while setting up a scene with multiple targets in A-frame - one of the 3D models failed to appear despite using a URL just like the ...

Styling the navigation bar using CSS

Currently working on establishing a top menu bar similar to StackOverflow, but with a fixed position for my webpage. Check out the JSFIDDLE Demo here Encountering extra space on the left and top of the menu bar. Seeking advice on how to eliminate this ex ...

Tips for ensuring only one submenu is open at a time

I have successfully created a responsive menu that is working well. However, I am facing an issue. I want only one menu to be open at a time. When a submenu is opened, the other menus should be hidden. How can I achieve this? Below is my Script code $( ...

Arrow icon indicating active status in side navigation bar

As part of my journey to enhance my Html and Css skills, I have been recreating templates from various websites. While this exercise has taught me a lot, I have hit a roadblock with one particular template. I am struggling to understand how they manage to ...