1

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.

Naemy
  • 446
  • 2
  • 5
  • 17

1 Answers1

2

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.

Community
  • 1
  • 1
Hogan
  • 69,564
  • 10
  • 76
  • 117
  • Not sure to understand how it works completely. I'm going to work on that deeper later but I tested it and it works, so thank you ! Totally saved me from hours of code and nonsense. Thank you. – Naemy Jun 01 '13 at 12:15
  • The current code has one downside though: You can't bind multiple times to one element with it. I edited the code for myself to accomplish this. Look at this [fiddle](https://jsfiddle.net/e71cugvx/1/). :) – Dennis98 Nov 21 '16 at 00:20
  • @Dennis98 -- I don't know -- using a global integer seems a little sketchy -- I'd implement an event list if you really need multiples. – Hogan Nov 21 '16 at 04:41
  • @Hogan Good to know that this is possible. :D Would be nice, I currently don't need that, but there's a good chance that I want to bind multiple events to the window object later on, so having the possibility is appreciated.. :) – Dennis98 Nov 22 '16 at 13:10
  • @Dennis98 -- using a list for events is a leading design -- you can look to the event model in C# and jQuery for examples. – Hogan Nov 22 '16 at 16:27