2

As is seen on a lot of sites currently, I would like to do something with an element when it comes into the view port or 100px from the viewport etc.

I have been searching for ages but so far nothing has worked.

I have a list of elements which are 500px high and 100% width. Im okay with the animation etc and what Im going to do with them, just need a bit of help triggering then when they are coming into view.

My aim is to give elements a class of animation-element and then be able to use that class to check if its in view.

Pseudo code:

$(window).on('scroll', function() {
    if (element is in the viewport) {
        $(this).doSomething();
    }
});

Seems lazy of me but I have been looking for too long without success.

Any previous attempts have just always triggered on when constant scrolling so even if the elements are no in the viewport and i'm setting a console log i'll have 100's of logs when scrolling a tiny bit.

Lovelock
  • 7,689
  • 19
  • 86
  • 186

1 Answers1

2

I have created a similar solution lately for another answer.

The JS tracks the scroll of the window, and compares how far the windows has scrolled, compared with the offset().top (Which tracks how far that element is from the top of the page). If the window scroll comes within -300px of the element top it fades/animates the animate in from the left.

JS:

var $win = $(window);
var $stat = $('.animation-element'); // Change this to affect your desired element.

$win.on('scroll', function () {
    var scrollTop = $win.scrollTop();

    $stat.each(function () {
        var $self = $(this);
        var prev=$self.offset();
        console.log(scrollTop);
        console.log(prev.top);
        if ( (scrollTop - prev.top) > -300) {
          $self.css('opacity', '1').addClass('animated fadeInLeft ');
        } else {
          console.log('n');
        }

    });

}).scroll();

Here's the working JSfiddle — scroll down to see elements slide in. https://jsfiddle.net/wigster/5dbt7ft3/1/

Alexander Wigmore
  • 3,157
  • 4
  • 38
  • 60
  • Actually, I have given all my list elements a class of 'animation-element' and when using your code it fires 3 events when the page is loaded. Not half scrolled down etc but a fresh page load? – Lovelock Dec 14 '15 at 15:36
  • I've edited the example jsfiddle and code to hopefully be a bit more relevant to your question. Please have a look now and let me know what the issue could be. – Alexander Wigmore Dec 14 '15 at 16:54