2

How can I check when an entire element is in view?

In the example below, if a box comes into view, I want to change the background color of the box to red. Also, the top box (which should already be fully displayed on your screen) should automatically be red (since it's already fully in the view).

How can I do this?

https://jsfiddle.net/7gr1qkeq/

HTML:

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

CSS:

body {
  margin: 50px;
}

.container {
  width: 300px;
  background: lightgrey;
  padding: 50px;
}

.box {
  display: block;
  width: 100%;
  height: 300px;
  background: grey;
}

.box:not(:last-of-type) {
  margin-bottom: 50px;
}
  • Possible duplicate of [How to tell if a DOM element is visible in the current viewport?](http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport) – Andy Ray Nov 19 '16 at 02:41
  • @AndyRay None of those answers check if the ENTIRE element is in view, i.e. the entire point of this question. –  Nov 19 '16 at 03:00
  • Read the first answer. Please close this question. – Andy Ray Nov 19 '16 at 03:17

2 Answers2

0

Quick example. Not perfect code by any means. Should give you an idea.

checkBoxes();

$(window).on('scroll', function() {
    checkBoxes();
});

function checkBoxes() {
    $('.box').each(function(i, v) {
      if (_isInTheScreen($(window), $(v), -$(v).height() )) {
        $(v).css('background', 'red');
      }
    });
}

/*
 * @param $ct : container - jQuery obj
 * @param $el : element selected - jQuery obj
 * @param optionOffset : offset
 */
function _isInTheScreen($ct,$el,optionOffset) {
  var i = $ct,
      g = $el,
      e = i.scrollTop(),
      d = i.scrollLeft(),
      f = g.offset(),
      l = f.top,
      c = f.left,
      j = true;

  j = (e-100<=(l))&&((e+i.height()+optionOffset)>=((l))&&(d<=c)&&((d+i.width())>=c));
  return j;
}

NOTE: you should always throttle when binding on scroll

fiddle here: https://jsfiddle.net/cd2733mv/2/

Marco Magrini
  • 749
  • 1
  • 9
  • 19
0

If you just want to check if the elements are within window height, not necessarily window width:

function highlightBoxes() {
  var windowStart = $(window).scrollTop();
  var windowEnd = windowStart + $(window).height();

  $('.box').each(function() {
    var box = $(this);
    var start = box.offset().top;
    var end = start + box.height();

    if (windowStart <= start && windowEnd >= end) {
      box.addClass('active');
    } else {
      box.removeClass('active');
    }
  });
}

highlightBoxes();
$(document).scroll(highlightBoxes);
$(window).resize(highlightBoxes);

Fiddle: https://jsfiddle.net/7gr1qkeq/4/

Edit:

If you want to check complete visibility, i.e. width + height: https://jsfiddle.net/7gr1qkeq/5/

user372495
  • 700
  • 4
  • 11