search

Home  >  Q&A  >  body text

How to make an element stick to the bottom of the page when scrolling up?

What I want to accomplish is as follows: https://imgur.com/a/YFcfO3N

Basically, I want a menu at the bottom of the page that sticks to the bottom of the page when you scroll up.

P粉356361722P粉356361722486 days ago516

reply all(1)I'll reply

  • P粉649990163

    P粉6499901632023-09-07 00:40:39

    I just checked the developer consolehttps://imgur.com/a/YFcfO3N It looks like they are using a footer container with the "Footer-wrapper" class, with the following CSS Attributes:

    .Footer-wrapper {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 3;
    }

    When scrolling down, another class is added to the container, "down":

    .down {
        bottom: -60px;
    }

    Negative positions must correspond to the height of the footer/menu.

    I think they do this using JavaScript. You can check in JavaScript whether the user is at the top of the page like this:

    let userIsAtTheTopOfThePage = window.pageYOffset === 0;

    You can add classes to elements like this:

    element.classList.add("my-class");

    and delete like this:

    element.classList.remove("my-class");

    Edit: Sorry, I misunderstood the question first, but what you want to achieve can be achieved in a similar way. Let’s take a look at this example menu:

    <nav id="menu">
        <ul>
            <li>Menu item 1</li>
            <li>Menu item 2</li>
            <li>Menu item 3</li>
            <!-- Add more menu items here -->
        </ul>
    </nav>

    Use this CSS

    #menu {
        position: fixed;
        bottom: 0;
        left: 0;
    }
    .scrolling-menu {
        position: static !important;
    }

    and this JavaScript

    document.addEventListener("DOMContentLoaded", function() {
        window.addEventListener("scroll", function() {
            var menu = document.getElementById("menu");
            var scrollPosition = window.scrollY;
            var windowHeight = window.innerHeight;
            var documentHeight = document.body.offsetHeight;
            var scrollThreshold = documentHeight - windowHeight - 200; // Adjust this value to determine when the menu should become part of the flow
    
            if (scrollPosition > scrollThreshold) {
                menu.classList.add("scrolling-menu");
            } else {
                menu.classList.remove("scrolling-menu");
            }
        });
    });

    It should be possible.

    reply
    0
  • Cancelreply