egr103 egr103 - 3 months ago 35
jQuery Question

When a DIV comes into view add class

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');


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


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. -