Reputation: 3978
I'd like to add a class to an element, like a DIV but also on an img, h1, etc. when it comes into the viewport when a user scrolls.
How do I calculate whether or not my element is in the viewport or not?
In pseudo: If #swing has entered the viewport add classes 'animated bounceOutLeft' (play animation using CSS3). When animation is complete remove classes 'animated bounceOutLeft'.
I just don't know where to start other than I know the code to add the class I want:
$('#star').addClass('animated bounceOutLeft');
PROGRESS EDIT
Thanks to @Bibhas I'm trying to implement this OnScreen plugin, which I think i've done because Dev tools says the classnames are there but these classnames are css3 transitions they just aren't playing, what could be the problem??
$(function() {
setInterval(function() {
$("#star") // get all <h2>s
.filter(":onScreen") // get only <h2>s on screen
.addClass('animated bounceOutLeft');
}, 1000) // repeat every second
})
Upvotes: 2
Views: 6332
Reputation: 1078
The getBoundingClientRect()
function may help here. Here's a CodePen I did:
$(window).on('load resize scroll',function(e){
$('h2').each(function(index) {
var h2Height = parseInt($(this)[0].getBoundingClientRect().height);
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
// This will return true as soon as the heading crosses the bottom of the viewport
if ($(this)[0].getBoundingClientRect().top < (viewHeight - h2Height)) {
$('h2').eq(index).addClass('added-class');
}
});
});
Edit: note that this assumes that the browser is running in Standards Mode.
Edit2: Following a suggestion from @brandnewjames, I've added some other event handlers into the on()
, which will also account for actions outside of just scrolling.
Upvotes: 0
Reputation: 14939
Apparently someone wrote a little jQuery plugin for that. From his code -
function isOnScreena(elem) {
var $window = $(window)
var viewport_top = $window.scrollTop()
var viewport_height = $window.height()
var viewport_bottom = viewport_top + viewport_height
var $elem = $(elem)
var top = $elem.offset().top
var height = $elem.height()
var bottom = top + height
return (top >= viewport_top && top < viewport_bottom) ||
(bottom > viewport_top && bottom <= viewport_bottom) ||
(height > viewport_height && top <= viewport_top && bottom >= viewport_bottom)
}
The source code is hardly 20 lines. You can read and learn. - https://github.com/benpickles/onScreen
Upvotes: 7