Skip to content

[Guide] How to use .wow (onScroll) animations #7

Open
@rallisf1

Description

CSS transitions work out of the box but I wanted to animate some icons when they appear on screen so I used the following code

<script>
  import MDBIcon from "mdbsvelte/src/MDBIcon.svelte";
  import { onMount } from 'svelte'

  let bodyHeight = 0
  let hasScrolled = false
  let waitingOnAnimRequest = false

  onMount(() => {
    bodyHeight = window.innerHeight
		|| document.documentElement.clientHeight
		|| document.body.clientHeight;
  })

  const animChecker = target => {
    target.querySelectorAll('[data-wow]').forEach(element => {
	  const elementTop = element.getBoundingClientRect().top
	  console.log(elementTop);
	  console.log(bodyHeight);
      if (elementTop < bodyHeight * 0.8) {
        if (!element.classList.contains('animated')) {
          element.classList.add('animated',element.dataset.wow)
        }
      }
    })
  }

  const onScroll = ({ target }) => {
    if (!waitingOnAnimRequest) {
      window.requestAnimationFrame(() => {
        animChecker(target)
        waitingOnAnimRequest = false
      })
      waitingOnAnimRequest = true
    }

    hasScrolled = document.body.scrollTop !== 0
  }
 
</script>

<style>
:global([data-wow]) {
  visibility: hidden;
}
:global(.animated) {
  visibility: visible!important;
}
</style>

<svelte:window on:scroll="{onScroll}" />

<MDBIcon fab icon="opencart" size="4x" data-wow="bounceInLeft" />

You can use any of the available CSS transitions as a data-wow attribute.

Tip: You can convert this into a a svelte component and import it wherever or maybe the [Author] @SauravKanchan wants to integrate into the package.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions