0

I was just going through the code of circliful and came across the following lines of code:

function isElementInViewport() {
    // Get the scroll position of the page.
    var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
    var viewportTop = $(scrollElem).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    // Get the position of the element on the page.
    var elemTop = Math.round(circle.offset().top);
    var elemBottom = elemTop + circle.height();

    return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}

Now my question is about this one line of code:

var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');

why incase of webkit browsers the scrollTop() value shoud be of the html element ??

Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174
  • 1
    You're actually reading that backwards. It's saying "if this is a webkit browser, use the ``. Otherwise, use the ``" – Mike Cluck Aug 22 '16 at 22:42
  • Possible duplicate of [why to use 'html, body' for scrollTop instead of just 'html'](http://stackoverflow.com/questions/12222485/why-to-use-html-body-for-scrolltop-instead-of-just-html) – Mike Cluck Aug 22 '16 at 22:43
  • @MikeC i think thats a jQuery question u;ve linked to .. also thanks for the tip ! :) – Alexander Solonik Aug 22 '16 at 22:45
  • They use jQuery but it's still Javascript and explains why. Some browsers apply the overall scroll to the document element, others to the body. This code picks which one to select. – Mike Cluck Aug 22 '16 at 22:46
  • Browser sniffing is seriously flawed, use feature detection. This question is not in scope for SA. – RobG Aug 22 '16 at 22:49
  • @RobG how can this like `((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');` be replaced with feature detection ?? – Alexander Solonik Aug 22 '16 at 23:05
  • WebKit has a scrollTop on both body and HTML. You can just use the larger of the two values or zero: `scrollTop = document.body.scrollTop || document.body.parentNode.scrollTop || 0`, noting that it must be an integer >= 0. Anyway, since you're using jQuery, just use `$(document).scrollTop()`, or even `(document.documentElement || document.body.parentNode || document.body).scrollTop`. Whatever. – RobG Aug 22 '16 at 23:53

0 Answers0