MarcL MarcL - 5 months ago 41
jQuery Question

JQuery: fire action when element is in view

In the footer of my site I'm using counUp.js (Link: http://inorganik.github.io/countUp.js/ ) to count up three numbers. I added this code at the bottom of the site:

<script type="text/javascript">
var c1 = new countUp("upnum1", 1, 27, 0, 4);
var c2 = new countUp("upnum2", 1, 10, 0, 4);
var c3 = new countUp("upnum3", 1, 27, 0, 4);
var c4 = new countUp("upnum4", 1, 1000, 0, 4);
window.onload = function() {
c1.start();
c2.start();
c3.start();
c4.start();
}
</script>


This works well, but starts counting once the page is loaded of course. How do I manage to fire this effect when the containing div of the numbers is 'in view' and not when the page is loaded? Tried several jQuery things but can't find a working solution... Thanks!

Answer

There is a simple check to see whether or not an element is in the viewport.

You can choose either to use a plugin or pure JQuery.

Relevant HTML :

<div id="inViewport">Is this in the viewport?</div>

Pure JQuery :

Here is the fiddle for this : http://jsfiddle.net/zWtkc/1/

$.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));

};

$(document).ready(function(){
    $(window).scroll(function(){
        if ($('#inViewport').isOnScreen()) {
            // The element is visible, do something
            alert("in viewport!");
        } else {
            // The element is NOT visible, do something else
        }
    });
});

Plugins :

You can use this plugin : https://github.com/teamdf/jquery-visible/

$(document).ready(function(){
    if ($('#inViewport').visible(true)) {
        // The element is visible, do something
    } else {
        // The element is NOT visible, do something else
    }
});

Or you can use this plugin : http://www.appelsiini.net/projects/viewport which allows for viewport selectors and your code will look like this :

$('#inViewport:in-viewport').doSomething();
Comments