Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript detect browser scroll to the top?

How do I modify the following code to detect scrolling to the top page instead.

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        alert(bottom);
    }
};

EDIT:

I am working on IE 10 for Windows Phone 8 BTW

like image 974
PutraKg Avatar asked May 07 '13 14:05

PutraKg


1 Answers

Managed to figure it out. Here's my code:

window.onscroll = function() {

    var body = document.body; //IE 'quirks'
    var document = document.documentElement; //IE with doctype
    document = (document.clientHeight) ? document : body;

    if (document.scrollTop == 0) {
        alert("top");
    }        
};

Chek it running:

window.onscroll = function(ev)
{
	var B= document.body; //IE 'quirks'
        var D= document.documentElement; //IE with doctype
        D= (D.clientHeight)? D: B;
	
	if (D.scrollTop == 0)
		{
			alert("top");
		}        
};
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

EXPLANATION OF HOW THIS CODE WORKS:

window.onscroll is the command to assign the onscroll event to the window element.

Now, as the onscroll event gets fired when an element's scrollbar is being scrolled., the element will be the window itself in this case.

Now, the function will be called when the event is fired.

In the function, we get the "document.body" to as en IE is the way to get it. After this, we get the documentElement, if there is a doctype.

Then, this line, is the one that chooses between the document or the body if the document.clientHeight is informed. If it's informed, it will put document on variable document. If not, it will put the body itself. After this, it will check the scrollTop property in order to know if current scroll position is "at the top"

like image 146
PutraKg Avatar answered Sep 19 '22 10:09

PutraKg