Skip to content

Instantly share code, notes, and snippets.

@eltonmesquita
Last active November 1, 2020 09:32
Show Gist options
  • Save eltonmesquita/bd803a21f27b12a58df1 to your computer and use it in GitHub Desktop.
Save eltonmesquita/bd803a21f27b12a58df1 to your computer and use it in GitHub Desktop.
A simple jQuery function that adds a class when the target(s) is in the viewport
function onViewport(el, elClass, offset, callback) {
/*** Based on http://ejohn.org/blog/learning-from-twitter/ ***/
var didScroll = false;
var this_top;
var height;
var top;
if(!offset) { var offset = 0; }
$(window).scroll(function() {
didScroll = true;
});
setInterval(function() {
if (didScroll) {
didScroll = false;
top = $(this).scrollTop();
$(el).each(function(i){
this_top = $(this).offset().top - offset;
height = $(this).height();
// Scrolled within current section
if (top >= this_top && !$(this).hasClass(elClass)) {
$(this).addClass(elClass);
if (typeof callback == "function") callback(el);
}
});
}
}, 100);
}
@AdrianGen
Copy link

AdrianGen commented Jul 23, 2018

@eltonmesquita

Hi, I'm trying to implement your solution with my code but I am not sure how to combine the two.

I have a simple jQuery function to animate some CSS progress bars for me:

$(".progressBar > span").each(function() {
  $(this)
    .data("origWidth", $(this).width())
    .width(0)
    .animate({
      width: $(this).data("origWidth")
    }, 1200);
});

But I don't know how should I link yours with mine to make it work.

I would appreciate any advice, please don't kill me I am new to this.

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment