Sarah Diba
Sarah Diba

Reputation: 97

Using pure javaScript without "onMount" in Sveltekit framework

Is there a way to using simple JavaScript without using onMount ?
How to improve this code and don't use onMount?
(I'd like to shoe each content box after user scrolls)
enter image description here

<script>
    import { onMount } from 'svelte';
    onMount(() => {
        const boxes = document.querySelectorAll('.content');
        window.addEventListener('scroll', checkBoxes);
        checkBoxes();
        function checkBoxes() {
            const triggerBottom = (window.innerHeight / 5) * 4;
            boxes.forEach((box) => {
                const boxTop = box.getBoundingClientRect().top;

                if (boxTop < triggerBottom) {
                    box.classList.add('show');
                } else {
                    box.classList.remove('show');
                }
            });
        }
    });
</script>

Upvotes: 1

Views: 1120

Answers (2)

Stephane Vanraes
Stephane Vanraes

Reputation: 16411

Assuming your content boxes are generated in an array you could use a combination of bind:this and svelte:window

<script>
 let boxes = [];
 let content = [];

 function checkBoxes() {
   // use boxes here
 }
</script>

<svelte:window on:scroll={checkBoxes} />

{#each content as c, i}
 <div bind:this={boxes[i]}>
   ....
 </div>
{/each}

Alternatively, look into actions and IntersectionObservers

Upvotes: 4

Anarion
Anarion

Reputation: 1038

How about -

document.addEventListener("DOMContentLoaded", function(){
    // your code here will be executed on page ready/load
});

Upvotes: 0

Related Questions