Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getBoundingClientRect in each: undefined is not a function

Tags:

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.

like image 427
Bram Vanroy Avatar asked Aug 04 '14 12:08

Bram Vanroy


People also ask

What is element getBoundingClientRect ()?

The Element. getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.

How do I get getBoundingClientRect in react?

You can use Element. getClientRects() and Element. getBoundingClientRect() to get the size and position of an element.

What is getBoundingClientRect () Top?

The getBoundingClientRect() method returns the size of an element and its position relative to the viewport. The getBoundingClientRect() method returns a DOMRect object with eight properties: left, top, right, bottom, x, y, width, height.


2 Answers

You could stick with jQuery and use the array [] notation ie:

var myClient = $(currentGrid)[0].getBoundingClientRect(); alert(myClient.top) 
like image 128
mustbebuilt Avatar answered Sep 18 '22 05:09

mustbebuilt


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.

like image 43
undefined Avatar answered Sep 22 '22 05:09

undefined