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.
The Element. getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.
You can use Element. getClientRects() and Element. getBoundingClientRect() to get the size and position of an element.
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.
You could stick with jQuery and use the array [] notation ie:
var myClient = $(currentGrid)[0].getBoundingClientRect(); alert(myClient.top)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With