简体   繁体   中英

CSS animations to toggle when in viewport with vanilla JS

So I have got different animations made in CSS, though the problem is that they start right away when the page loads (ofcourse). I do not want this though. Is there a way in Vanilla JavaScript to get the animation to fire up only when it is in the viewport ? I have searched in a lot of places, but I either find a plugin I need to use or jQuery.

HTML:

    <div class="introduction">
    <h1>I can do the following for you:</h1>
    <ul>
        <li>Create a custommade, new website.</li>
        <li>Code a PSD template into a working website.</li>
        <li>Rework an outdated website.</li>
        <li>Clean up messy code of a website.</li>
    </ul>
    </div>

CSS:

@keyframes showOnLoad {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

.introduction li {
    list-style-type: none;
    margin-bottom: 5px;
    text-align: center;
    opacity: 0;
    -webkit-animation: showOnLoad;
    animation: showOnLoad;
    -webkit-animation-duration: 2s;
    animation-duration: 2s;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}

.introduction li:nth-child(2) {
    -webkit-animation-delay: 1s;
    animation-delay: 1s;
}

.introduction li:nth-child(3) {
    -webkit-animation-delay: 2s;
    animation-delay: 2s;
}

.introduction li:nth-child(4) {
    -webkit-animation-delay: 3s;
    animation-delay: 3s;
}

This is the code you need.

window.addEventListener("scroll", onScroll);

function onScroll() {
  for (var item of document.querySelectorAll(".introduction li")) {
    elementVisible(item);
  }
}

function elementVisible(el) {
  let top = el.offsetTop;
  let height = el.offsetHeight;
  let bottom = top + height;

  let IsOverBottom = top > (window.pageYOffset + window.innerHeight);
  let IsBeforeTop = bottom < window.pageYOffset;

  if (!IsOverBottom && !IsBeforeTop) {
    el.classList.add("show");
  }
}

And a bit of CSS

@keyframes slideIn {
  0% {
    opacity: 0;
    transform: translateX(100%);
  }
  100% {
    opacity: 1;
    transform: translateX(0%);
  }
}

.show {
  animation: slideIn 5s ease-in-out;
}

This is a basic implementation but it gets you closer.

http://jsbin.com/hetapaj/1/edit?css,js,output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM