maciekgrzybek / svelte-inview

A Svelte action that monitors an element enters or leaves the viewport.🔥
MIT License
749 stars 23 forks source link

on:enter called immediately on page load #18

Closed CryptAlchemy closed 2 years ago

CryptAlchemy commented 2 years ago

Hi there!

Noticed the on:enter is being right when the page loads; and this makes it so unobserveOnEnter. Additionally, I tried putting rootMargin:'50px' and that did not work.

Since the event is called right away, it breaks functions that require a one-time accurate call of the intersection.

Thanks!

maciekgrzybek commented 2 years ago

Hey @CryptAlchemy ,thanks for creating the issue. Can you show me the example where this is happening? Also, which version are you using? Thanks :)

CryptAlchemy commented 2 years ago

Hi.

Using "svelte-inview": "^3.0.0", in package.json.

Here is an example:

<script>
     import { fly } from 'svelte/transition';
     import { inview } from 'svelte-inview';

     let getToKnowVisible;
</script>
<div use:inview={{rootMargin: '50px',unobserveOnEnter: true}} on:enter={() => getToKnowVisible = true}>
     {#if getToKnowVisible}
     <h2 in:fly="{{ y: 100, duration: 1500 }}" class="section-heading">Hello there!</h2>
     {/if}
</div>
maciekgrzybek commented 2 years ago

Can you provide the whole app? or at least the page? I'm just testing it locally with this example:

<script>
  import { inview } from 'svelte-inview';

  function handleOnEnter(event) {
    console.log('hello I am here');
  }
</script>

<main>
  <div class="container" />
  <div use:inview={{ unobserveOnEnter: true }} on:enter={handleOnEnter} />
</main>

<style>
  :root {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
      Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  }
  .container {
    height: 110vh;
    background-color: lightblue;
  }
</style>

And I can't reproduce your bug.

CryptAlchemy commented 2 years ago

Hi there!

I found the reason that this has happened.

I have two locally-stored images in <img> HTML tags right above the inview div. What seems to happen is that the images are not physically present for a split-second while the page loads; making it so the inview believes that the inview div is currently visible (the inview div is visible for a split-second and then the images show up).

This looks like it's not a bug with the framework; although, do you know if there's a way to prevent the images from being invisible while they are loading?

CryptAlchemy commented 2 years ago

Follow-Up:

Looks like it was as simple as adding a defined width and height attribute to the <img> tags.

Thanks for looking into this! Dzieki!

maciekgrzybek commented 2 years ago

Awesome mate :) Glad you've managed to find the issue :)