Reputation: 403
I currently have a script set up to add a class to a div once its in the viewport. I have multiple divs that this applies to however, so once the first one is visible, the class gets added to every single one. Is there a more streamline way of separating these rather than duplicating the function for each element?
HTML
<div class="header-title"><span>FOO</span></div>
<div class="header-title"><span>BAR</span></div>
CSS
.header-title span {
display: inline-block;
position: relative;
}
.change:after {
content: " ";
position: absolute;
height: 5px;
border-bottom: 1px solid red;
-webkit-animation: extend .75s 1 forwards;
animation: extend 4s 1 forwards;
margin-left: 4px;
top: 1.2em !important;
}
@-webkit-keyframes extend {
0% {
width: 0;
}
100% {
width: 200px;
}
}
@keyframes extend {
0% {
width: 0;
}
100% {
width: 200px;
}
}
jQuery
function isElementInViewport(elem) {
var $elem = jQuery(elem);
// Get the scroll position of the page.
var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
var viewportTop = jQuery(scrollElem).scrollTop();
var viewportBottom = viewportTop + jQuery(window).height();
// Get the position of the element on the page.
var elemTop = Math.round( $elem.offset().top ) ;
var elemBottom = elemTop + $elem.height();
return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}
// Check if it's time to start the animation.
function extendLine() {
var $elem = jQuery('.header-title span');
// If the animation has already been started
if ($elem.hasClass('change')) return;
if (isElementInViewport($elem)) {
// Start the animation
$elem.addClass('change');
}
}
// Capture scroll events
jQuery(window).scroll(function(){
extendLine();
});
http://codepen.io/SeanLindsay1/pen/bBOWLW
Upvotes: 3
Views: 816