Skip to main content

Cross-browser method for detecting the scrollTop of the browser window



What is the best cross-browser way to detect the scrollTop of the browser window? I prefer not to use any pre-built code libraries because this is a very simple script, and I don't need all of that deadweight.





Source: Tips4all

Comments

  1. function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
    //most browsers
    return pageYOffset;
    }
    else{
    var B= document.body; //IE 'quirks'
    var D= document.documentElement; //IE with doctype
    D= (D.clientHeight)? D: B;
    return D.scrollTop;
    }
    }

    alert(getScrollTop())

    ReplyDelete
  2. If you don't want to include a whole JavaScript library, you can often extract the bits you want from one.

    For example, this is essentially how jQuery implements a cross-browser scroll(Top|Left):

    function getScroll(method, element) {
    // The passed in `method` value should be 'Top' or 'Left'
    method = 'scroll' + method;
    return (element == window || element == document) ? (
    self[(method == 'scrollTop') ? 'pageYOffset' : 'pageXOffset'] ||
    (browserSupportsBoxModel && document.documentElement[method]) ||
    document.body[method]
    ) : element[method];
    }
    getScroll('Top', element);
    getScroll('Left', element);


    Note: you'll notice that the above code contains a browserSupportsBoxModel variable which is undefined. jQuery defines this by temporarily adding a div to the page and then measuring some attributes in order to determine whether the browser correctly implements the box model. As you can imagine this flag checks for IE. Specifically, it checks for IE 6 or 7 in quirks mode. Since the detection is rather complex, I've left it as an exercise for you ;-), assuming you have already used browser feature detection elsewhere in your code.

    Edit: If you haven't guessed already, I strongly suggest you use a library for these sorts of things. The overhead is a small price to pay for robust and future-proof code and anyone would be much more productive with a cross-browser framework to build upon. (As opposed to spending countless hours banging your head against IE).

    ReplyDelete
  3. to save you all the trouble use a framework such as jquery or mootools
    that calculates all these values in one line (cross browser)
    in mootools its $('element').getTop();
    in jquery you will need a plugin named dimensions if i remember correctly
    although most of the time even without a framework you can actually use element.getScrollTop(); to get what you'll need
    the only problem is on IE7 and below this calculation is somewhat buggy as it doesn not take the position value of the element into consideration
    for example if you got a position: absolute css attribute for that element
    the calculation is performed on the parent element of that element

    ReplyDelete
  4. YUI 2.8.1 code does this:

    function getDocumentScrollTop(doc)
    {
    doc = doc || document;

    //doc.body.scrollTop is IE quirkmode only
    return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
    }


    I think jQuery 1.4.2 code (a bit translated for humans) and supposing I understood it properly does this:

    function getDocumentScrollTop(doc)
    {
    doc = doc || document;
    win = doc.defaultView || doc.parentWindow; //parentWindow is for IE < 9

    result = 0;
    if("pageYOffset" in win) //I'don't know why they use this, probably they tested it to be faster than doing: if(typeof win.pageYOffset !== 'undefined')
    result = win.pageYOffset;
    else
    result = (jQuery.support.boxModel && document.documentElement.scrollTop) ||
    document.body.scrollTop;

    return result;
    }


    Unfortunatley extracting the value of jQuery.support.boxModel is almost impossible because you would have to add a temporary child element into document and do the same tests jQuery does.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.