Let's see if I understand well. You have a page long enough to scroll, and there is an element that, when it appears in the viewport, you want to do something with it. Thus, the only event that is triggered for sure at the moment when the element falls into the viewport is "scrolling". Therefore, if the item is on the page and the scroll is in the viewport, then you need to associate the action with the scroll event to check if the item is in the view every time the event is fired. Mostly like this:
$(window).scroll(function() { check_element_position(); });
Now, to find out if an item is in the viewport, you need 3 things. The offset of the top of this item, the size of the viewport, and the top of the scroll window. It should pretty much look like this:
function check_element_position() { var win = $(window); var window_height = win.height(); var element = $(your_element); var elem_offset_top = element.offset().top; var elem_height = element.height(); var win_scroll = win.scrollTop(); var pseudo_offset = (elem_offset_top - win_scroll); if (pseudo_offset < window_height && pseudo_offset >= 0) {
Here (elem_offset_top - win_scroll) represent the position of the element if there was no scrolling. Thus, you just need to check if the top of the elementβs offset is above the window viewer to see if it has a view or not. Finally, you can be more accurate in your calculations by adding the height of the element (the variable is already there), because just the code that I just made will fire an event, even if the element is visible only by 1 pixel.
Note. I did it in five minutes, so you may have to fix some of this, but it gives you a good idea of ββwhat is going on;)
Feel free to comment and ask questions.
source share