Skip to content

Instantly share code, notes, and snippets.

@digamber89
Created May 3, 2019 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digamber89/02cc790324202a30fbfd30df24fefe5d to your computer and use it in GitHub Desktop.
Save digamber89/02cc790324202a30fbfd30df24fefe5d to your computer and use it in GitHub Desktop.
Check if Item is in viewport -> add class if it is - remove class if it isn't
(function ($) {
var digthisAddClassToElement = function (element) {
//cache the DOM
//use the element send through function as the dom element
var $element = $(element);
//scoped helper functions
var isInViewport = function (elem) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
var addRemoveClassFromElement = function () {
$element.each(function (index, element) {
var $el = $(element);
if (isInViewport(element)) {
$el.addClass('digthis');
} else {
$el.removeClass('digthis');
}
});
};
//event listener
$(window).on('scroll', addRemoveClassFromElement);
//default action
addRemoveClassFromElement();
};
$(function () {
digthisAddClassToElement('.item');
});
})(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment