0

I can't seem to figure out why this code as a while loop and as a recursive function is running infinitely. I am checking if an element is in the viewport, if it is not, then I move its parent's top offset up until its child is out of the viewport.

HTML structure:

<div id="outter">
    <div id="inner"></div>
    <div id="inner"></div>
    <div id="inner"></div>
</div>

They all have set heights and widths and are display:inline-block and visible.

I've already have a jQuery psuedoclass that checks if an element is offscreen, as `.is(':offscreen'). It works fine, but I'm wondering if the original value is caching somewhere in jQuery.

Here in the code:

var top=1;
do{
    $('#outter').css('top', top);
    top++;  
}
while(!$('#inner').is(':offscreen'));

Here is the code for the offscreen psuedoclass, found on StackOverflow:

jQuery.expr.filters.offscreen = function(el) {
  var rect = el.getBoundingClientRect();
      return(
        (rect.x + rect.width) < 0  || (rect.y + rect.height) < 0 || 
        (rect.x > window.innerWidth || rect.y > window.innerHeight));
};
wordSmith
  • 2,993
  • 8
  • 29
  • 50

2 Answers2

0

According to this, getBoundingClientRect may or may not have the x and y properties on some browsers (I've just tested it on Chrome 57 and it returned undefined). Use left as a replacement for x and top as a replacement for y as DOMRect always have them.

Community
  • 1
  • 1
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • Thank you, this helps, but I am still getting an infinite loop. – wordSmith Apr 22 '17 at 11:58
  • @wordSmith I'll say it's a far shot but try adding the `"px"` after `top` in: `$('#outter').css('top', top + "px");`! – ibrahim mahrir Apr 22 '17 at 12:00
  • @wordSmith and one thing I've just noticed. You're setting the top of `#outer` and checking for the offscreening of `#inner`. Could `#inner` have a fixed or absolute `position`? – ibrahim mahrir Apr 22 '17 at 12:02
  • @wordSmith and by the way, in order for `top` to work, the element should have either a `fixed`, `relative` or `absolute` positioning. – ibrahim mahrir Apr 22 '17 at 12:41
0

JQuery won't work when you're selecting tags with duplicate IDs.

Change your inside divs id="inner" to class="inner" and change your selector to $('.inner'), or give your inner divs unique IDs.

Wrinn
  • 98
  • 1
  • 13