Search code examples
javascriptjquerygetboundingclientrect

getBoundingClientRect in each: undefined is not a function


So I am trying to call some functions when fullscreen sections are in the viewport. Let's say I have 7 sections, then I want something to happen when a certain section is inside the viewport (I have a function that snaps the sections into the viewport so there can never be multiple sections in the viewport, but I am trying to find out which section is visible in the viewport).

Here is a fiddle: http://jsfiddle.net/h7Hb7/2/

function isInViewport() {
    $("section").each(function () {
        var $this = $(this),
            wHeight = $(window).height(),
            rect = $this.getBoundingClientRect(); // Error in console

        // Borrowed from http://stackoverflow.com/a/7557433/5628
        if (rect.top >= 0 && rect.bottom <= wHeight) {
            console.log($this.attr("id") + "in viewport");
        }
    });
}

$(window).scroll(function () {
    // Other functions are called inside the setTimeout function, can't remove
    clearTimeout($.data(this, "scrollTimer"));
    $.data(this, "scrollTimer", setTimeout(function () {
        isInViewport();
    }, 1200));
});

I don't know where to start looking but I am guessing it's to do with the each function. Is it the each function that poses a problem? It can't be a CSS issue, because the problem occurs on scroll when the CSS has already loaded.


Solution

  • jQuery object doesn't have getBoundingClientRect method, you should get the HTMLElement object and then call the method or:

    this.getBoundingClientRect();
    

    As a suggestion, if using a plugin is an option, you can consider using the jquery.inview plugin.