Site logo

Archived topic

Make a Button on a Page sticky on the bottom of the screen on mobile & Tab

3 replies · Started by Ben on September 14, 2021

Viewing posts 1–4 of 4

Hey guys,

Can I take this button:

And make stick to the bottom the screen on mobile AND tablet, like this?

Thanks

Hi Ben,

This is going to be tricky to do but try adding this script.

<script>
    const stickyBtn = document.querySelector('.sticky-btn');
    
    var lastScrollTop = 0;
    
    document.addEventListener("scroll", function(){ // or window.addEventListener("scroll"....
            var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
            if (st > lastScrollTop){
                stickyBtn.classList.add('sticky-mode');
            } else if(st === 0 || isInViewport(stickyBtn.parentNode)) { 
                console.log("Top of page");
                stickyBtn.classList.remove('sticky-mode');
            } else {
                console.log("scrolling up "+st);
            }
        
            lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
    }, false);
        
        
        var isInViewport = function (elem) {
        var bounding = elem.getBoundingClientRect();
        return (
            bounding.top >= 0 &&
            bounding.left >= 0 &&
            bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    };
    </script>

You then add sticky-btn class to the button block.

You then add this CSS:

    .sticky-mode {
        z-index: 9999;
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        width: auto;
    }

Hey Elvin,

Where do I add the script to?

Thanks

Ben

The script can be added through a Hook element. You then set its hook to "wp_footer".

As for the display rule, set it to the page where the button is located.

The CSS can be added through normal means. https://docs.generatepress.com/article/adding-css/

By the way, I forgot to include something important.

For the CSS, wrap it w/ @media rule.

Example:

@media (max-width:768px){
    .sticky-mode {
        z-index: 9999;
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        width: auto;
    }
}
This archived topic is closed to new replies.