Created
May 3, 2019 10:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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