Naemy
Naemy

Reputation: 536

Peform a function if an element is completely in the viewport (live)

I've tried to use a jQuery plugin within viewport to detect whether or not an element is in the viewport.

It works, but it doesn't update.

He recommandes ScrollStop. I add it, but it doesn't work.

I only put my code here:

$(document).ready(function() {
  $(window).bind("resize scrollStop", function() {
$("div").withinViewport().append("<span>hi</span>");
});
});

(plus, it's using the bind method, so it's a bit outdated..)

So, it may be simple, but I didn't get it to work.

I'm new to jQuery and javascript so.. It may be super simple.

Here's the website with the code and everything

edit: works on resize ! but not on scroll.

Upvotes: 1

Views: 733

Answers (1)

Hogan
Hogan

Reputation: 70523

From here

jQuery - bind event on Scroll Stop

$.fn.scrollStopped = function(callback) {           
        $(this).scroll(function(){
            var self = this, $this = $(self);
            if ($this.data('scrollTimeout')) {
              clearTimeout($this.data('scrollTimeout'));
            }
            $this.data('scrollTimeout', setTimeout(callback,250,self));
        });
    };

$(window).scrollStopped(function(){
    $("div").withinViewport().append("<span>hi</span>");
});

How this works.

The function is first clearing any timeout associated with the data element scrollTimeout.

It think creates a new element there with a timeout of 250 ms with the function passed in.

Thus while scroll is moving it is always clearing the function from running and resetting it to run "in a little bit".

When the scrolling stops -- then it can't clear the function so the function executes.

Cute trick.

Upvotes: 2

Related Questions