$.fn.farthestDecendant

http://benalman.com/

by Ben Alman

HTML

<script src="https://rawgit.com/cowboy/1003361/raw/jquery.ba-farthest-descendant.js"></script>

CSS

body {
    text-align: center;
}

div {
    display: inline-block;
    border: 1px solid rgba(0,0,0,.1);
    background: rgba(0,0,0,.05);
    padding: 4px;
    -webkit-transition: all 0.1s;
}

div + div {
    margin: 4px 0 0 4px;
}

.farthest {
    border: 1px solid rgba(0,64,0,.5);
    background: rgba(0,128,0,.5);
}

.hover {
    border: 1px solid rgba(0,0,0,.5);
}

JavaScript

$(function() {
  // Generate a random DOM.
  // http://twitter.com/cowboy/status/65845594400362496
  (function(s,n){while(n--){s.push($('<div/>').appendTo(s[~~(Math.random()*(s.length-1))]))}})(['body'],999);

  // Farthest descendants.
  var body = $('body');
  var farthests = body.farthestDecendant('div').addClass('farthest');
  var top = Math.min(farthests.offset().top - 50, body.outerHeight() - $(window).height());

  body.animate({ scrollTop: top });

  // Crazy hovers.
  var hovers = [];
  walk(body[0], function(depth) {
    var arr = hovers[depth] || (hovers[depth] = []);
    arr.push(this);
    $(this).data('depth', depth);
  });
  
  body.delegate('div', 'hover', function(e) {
    e.stopPropagation();
    var depth = $(this).data('depth');
    $(hovers[depth]).toggleClass('hover', e.type == 'mouseover');
  });
  
  function walk(node, callback) {
    var skip, tmp;
    var depth = 0;

    do {
      if ( !skip ) {
        skip = callback.call(node, depth) === false;
      }

      if ( !skip && (tmp = node.firstChild) ) {
        depth++;
      } else if ( tmp = node.nextSibling ) {
        skip = false;
      } else {
        depth--;
        skip = true;
        tmp = node.parentNode;
      }

      node = tmp;

    } while ( depth > 0 );
  }
});