I want to fade in an element only when it's visible in the viewport. To do this, I'm using a isOnScreen()
function. It works fine, but only with one element, and if more elements with the same class are on the page, it works only with the first one.
How can I use the function isOnScreen()
for all the elements on page?
For example, I have an element .quote
at the beginning and one at the end of the page. The first element works fine, the element at the bottom not.
I've tried to use $('.quote').each(function() {
and inside isOnScreen()'
but it doesn't work.
EDIT
I found the solution, see my own answer below.
$.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
$(window).scroll(function() {
if ($('.quote-container').isOnScreen()) {
$('.quote').addClass('fade-in');
} else {
$('.quote').removeClass('fade-in');
}
});
.main-container {
height: 2000px;
}
.quote-container {
width: 100%;
background-color: yellow;
margin: 0;
}
.quote {
font-size: 175%;
font-style: italic;
text-align: right;
margin: 0;
padding: 35px 215px;
}
.page-content {
width: 100%;
background-color: lightblue;
margin: 0;
}
.page-content p {
position: relative;
top: 50%;
margin-left: 230px;
font-size: 220%;
margin-top: 0;
margin-bottom: 0;
}
.big {
height: 1000px;
}
.little {
height: 700px;
}
@-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@-moz-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
.fade-in {
opacity:0;
-webkit-animation:fadeIn ease-out 1;
-moz-animation:fadeIn ease-out 1;
animation:fadeIn ease-out 1;
-webkit-animation-fill-mode:forwards;
-moz-animation-fill-mode:forwards;
animation-fill-mode:forwards;
-webkit-animation-duration:1.6s;
-moz-animation-duration:1.6s;
animation-duration:1.6s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-container">
<div class="page-content little">
<p>Page Content</p>
</div>
<div class="quote-container">
<p class="quote">Lorem Ipsum.</p>
</div>
<div class="page-content big">
<p>Page Content</p>
</div>
<div class="quote-container">
<p class="quote">Dolor sit amet.</p>
</div>
<div class="page-content little">
<p>Page Content</p>
</div>
</div>
I've just solved using the answer of Luis Serrano with some little changes.
$('.quote-container').each(function() {
if ($(this).isOnScreen()) {
if ($(this).children('.fade-in').length < 1) {
$(this).children().toggleClass('fade-in');
}
}
});
In this way .quote
will fade in only once and only when in viewport.