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?
Asked
Active
Viewed 1,596 times
2
-
1Yes, it is possible. [How to ask questions on StackOverflow](http://stackoverflow.com/help/how-to-ask) – Jay Blanchard Sep 30 '14 at 21:45
-
Can you give me some code? example? – Gtopuria Sep 30 '14 at 21:47
-
Can you share with us what you have tried? – Jay Blanchard Sep 30 '14 at 21:47
-
container.addEventListener("scroll", fnDoStuff, true) – dandavis Sep 30 '14 at 21:49
1 Answers
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.
-
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