2

How do i cancel this function? So the scroll event is canceled and i'd have to call the function again?

function scroll_play() {

    $('.media-tbl > tbody > tr').each(function(i, element) {

        $(window).bind('scroll', function() {
            /* checks if elements are in view */
        });

    });
}

scroll_play();

I specifically want to stop $(window).bind('scroll', , so i can do it at another time by calling the function scroll_play()

How do i solve this?

user892134
  • 3,078
  • 16
  • 62
  • 128
  • 1
    Use [.unbind](https://api.jquery.com/unbind/) `$(window).unbind('scroll');` – Roy Bogado Aug 12 '19 at 12:20
  • .bind() is deprecated as of v3 https://api.jquery.com/bind/, use `on()` and `off()` https://api.jquery.com/on/#on-events-selector-data-handler – laruiss Aug 12 '19 at 12:23
  • So i can do `$(window).off('scroll');` and then call `$(window).bind('scroll', ` again? – user892134 Aug 12 '19 at 12:27
  • @user892134 You absolutely *do not* want a scroll listener for every row in a table. That would cause performance problems – charlietfl Aug 12 '19 at 12:32
  • what happens if you bind the scroll event listener for too many elements can be seen [in this question here](https://stackoverflow.com/questions/56683298/animations-are-slowing-the-performance-of-web-page/56736244#56736244) (hint, the answer was the same as it is now, use IO) – cloned Aug 12 '19 at 14:16

2 Answers2

4

You really should use Intersection Observer (IO) for this. This was developed to solve problems as yours, to handle elements scrolling into view (and also out of view)

First you set the options for your observer. For example, you can specify how much the element has to be visible when the callback function should fire:

var options = {
  rootMargin: '0px',
  threshold: 1.0
}

var observer = new IntersectionObserver(callback, options);

Here we say the element has to be 100% visible (threshold: 1.0) -> Then the callback is executed.

Then we define which elements to watch:

var target = document.querySelectorAll('.media-tbl > tbody > tr');
observer.observe(target);

and last we define what should happen when the defined element scrolls into view:

var callback = function(entries, observer) { 
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // target element:
  });
};

If you need to support older browsers, use the official polyfill from w3c.

cloned
  • 6,346
  • 4
  • 26
  • 38
  • in `entries.foreach` try logging entry.intersectionratio, if this is small it means it leaves the screen, otherwise it is entering the screen. Also check [this example for checking if an element is 75% in view](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Intersection_change_callbacks) – cloned Aug 12 '19 at 14:14
-2

Use

For jQuery > 1.7

$(window).off('scroll');

jQuery version <= 1.7

$(window).unbind('scroll');
UnmeshD
  • 159
  • 2
  • 11