0

I have a webpage where I have some buttons that I want to appear as the user scrolls down the page. My problem is effectively two-fold. First of all, as I have shown below, I need to work out when the element I want to appear is at the bottom of the page and for that I have done some rather finicky code with the scroll position. I would rather there be a more elegant way of detecting whether an element is appearing on screen or not. This would also help as it would allow my code to work with webpage sizes.

Secondly, and this is of less importance so if I am limited to one problem per query I would rather it be the above one and I'll edit this part out, but I want to add a transition animation to my buttons when they appear. If I use a standard #if visible transition on to the screen then it increases the size of the page and it feels jittery so I have instead temporarily made the opacity 0 so that it's not visible to the user.

So currently, to detect the scroll bar position my code is as follows:

    let scrollY = 0;
    let lower = -500;  // this normalises for the buttons being at the bottom of the screen and there being some space between them where I want them to be visible
    let visible = true;
    $: {
        if (lower + 250 * Math.floor((i+3) / 3) <= scrollY) {  // 250 is roughly pixel height of button. i+3 because the buttons are three per row so that way I can use the same code for every button
            visible = true;
        } else {
            visible = false;
        }
    }

    onMount(() => {
        // add scroll event listener
        window.addEventListener("scroll", () => {
            // update scrollY variable
            scrollY = window.scrollY;
        });
    });

This code below is what I am currently using for the visibility:

<button style={visible ? "" : "opacity: 0; pointer-events: none;"}>
{text} 
</button>

Before, I tried using some code like {#if visible} <button in:slide={{duration: 500}} out:slide={{duration: 500}} /> {/if} for an animation but as that changed the scrollbar I avoided doing that.

0