2

I'm trying to make fixed table header and is it possible to catch event or catch element when you scroll down and table header goes off screen?

Gtopuria
  • 429
  • 2
  • 8
  • 25

1 Answers1

2

One method would be using a scroll event for the window, and check if the element is visible there.

How to check if an element is on screen is answered here: Check if element is visible on screen

Here's how to turn that code into custom events entered_view and exited_view:

var $element = $('#some_element');
var is_visible = false;

$(window).on('scroll', function (e) {
    // Check if $element is on screen using code from other answer

    if (checkVisible($element)) {
         if (!is_visible) {
             $element.trigger('entered_view');
         }
         is_visible = true;
    } else {
         if (is_visible) {
             $element.trigger('exited_view');
         }
         is_visible = false;
    }
});

Once you get it working, you might also want to debounce the scroll event: Here's info about debouncing/throttling in jquery.

Community
  • 1
  • 1
michaelb
  • 747
  • 3
  • 9
  • you probably want to debounce that because scroll can fire dozens of times a second... – dandavis Sep 30 '14 at 22:01
  • @dandavis Yes that's absolutely correct, just was trying to keep the answer simpler / complexity down. edited to reflect – michaelb Sep 30 '14 at 22:05
  • you're right and nice to to provide code, i was just trying to make good gooder in case a noob came across the code and wondered why it bogged down their crappy device (detecting visibility can be expensive)... – dandavis Sep 30 '14 at 22:08