Skip to content

Instantly share code, notes, and snippets.

@israelcrux
Created January 6, 2017 02:01
Show Gist options
  • Save israelcrux/2adbdc83c1ac60a78783cdad6d8e9985 to your computer and use it in GitHub Desktop.
Save israelcrux/2adbdc83c1ac60a78783cdad6d8e9985 to your computer and use it in GitHub Desktop.
Trigger an event when element is in visible part of scrollable container. Angularjs 1.+ directive
/**
*
* Ever wanted to do something when an element comes handy in the visible part of
* a scrollabel list?
*
* Usage:
*
* <div class="list">
* <div
* in-view-after-scroll="doThisWhenThisElementIsVisibleAfterScrolling()" >
* An element of a list
* </div>
* </div>
*
*
*/
(function(angular){
var module = angular.module('anymodule',[])
module.directive('inViewAfterScroll', inViewAfterScroll);
function inViewAfterScroll(){
var directive = {
scope : {
method : '&inViewAfterScroll',
index : '@',
total : '@'
},
link : link
};
return directive;
/////////// functions /////////////
function link(scope,element,attrs,ctrl){
var scrollingElement = element.parent();
scrollingElement.scroll(function(){
if(
isElementNeartTop(element,scrollingElement,70) ||
(
scope.index * 1 === scope.total - 1 && //is the last element
scrollingElement.scrollTop() + 50 >= scrollingElement[0].scrollHeight - scrollingElement[0].offsetHeight
) ||
(
scope.index * 1 === 0 && //is the first element and its at least 21 pixels close
isElementNeartTop(element,scrollingElement,0)
)
){
scope.method();
}
});
/**
*
* ------------------
* | | <-- Scrollable container
* | |
* ----------------------- <-- scrollTop() + offset
* | |
* | "near top" zone |
* | |
* ----------------------- <-- scrollTop() + offset + 100
* | |
*
*/
function isElementNeartTop(element,scrollingElement,offset){
return scrollingElement.scrollTop() + offset <= element.get(0).offsetTop &&
scrollingElement.scrollTop() + offset + 100 >= element.get(0).offsetTop;
}
}
}//Directive
})(angular);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment