Last active
November 1, 2020 09:32
-
-
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
This file contains 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 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); | |
} |
@dasaki the code replicates the element each time.
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
Just in case someone is interested, I adapted the code so that the elements recover their original look after they are hidden again by the scroll, so one can, for example replay animations each time the elements get into the viewport (see it working: http://jsfiddle.net/jp78rLef/ ). It doesn't work with latest jquery though ( tested with jquery-2.1.0.js )