2

Basically i'd like to trigger this box animation after the user scrolls down by adding a class.

Can't seem to make this work for me, I'm probably doing something fundamentally wrong. Below is my current code, can anyone give me pointers as to what I'm doing wrong? Thanks!

HTML

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="600px" height="600px" viewBox="0 0 600 600" enable-background="new 0 0 600 600" xml:space="preserve">
    <rect class="box" x="147.297" y="237.162" fill="#FFFFFF" stroke="#000000" stroke-width="8" stroke-miterlimit="10" width="305.405" height="125.676"/>
</svg>

CSS

     @keyframes offset{
    100%{
      stroke-dashoffset:0;
    }
  }

.box{
    stroke:transparent;
}
  .box.draw{
    stroke:#202020;
    stroke-width:5;
    stroke-dasharray:910;
    stroke-dashoffset:910;
    animation: offset 5s linear forwards;
  }

jQuery/JS

$(function() {
    var boxDraw = $(".box");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 400) {
            box.addClass("draw");
        } 
    });
});

Additionally, how might it be possible to trigger an animation after a certain point in the page, rather than a scroll value? Any help would be appreciated.

Joshua Chin
  • 41
  • 2
  • 7
  • 1
    A certain point is a scroll value. You can check the offsetTop of the element you want to check and compare it with the current scrollTop, if you want to trigger the animation when a certain element is in sight, but you always end up with a scroll value. Also, you define `var boxDraw = $(".box");` but you apply the class to `box`, not `boxDraw` – Capsule Jul 04 '17 at 03:50

2 Answers2

0

@Capsule has figured it out. Your correct JS code:

$(function() {
    var boxDraw = $(".box");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 400) {
            boxDraw.addClass("draw");
        } 
    });
});

To trigger the scroll when a certain element is in view, again @Capsule has pointed it out but here's the code

$(function() {
    var boxDraw = $(".box");
    var boxDrawTop = boxDraw.offset().top;
    var windowHeight = $(window).height();

    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        // let's fire up animation when .box is in view

        if ( scroll >= ( boxDrawTop - windowHeight )) {
            boxDraw.addClass("draw");
        } 
    });
});
Junaid
  • 1,270
  • 3
  • 14
  • 33
0

search for js lib wow.js (in searching engine-text for minimal content here...)