Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect if the page is at the top?

I want to make an event occur when the page scroll is at the top of the page. Also I need an if statement for it. I am a beginner with javascript so any help is appreciated.

I am looking for something like this:

if (at_the_top_of_the_page) {
do_the_event_here
}

I think this is the right struckture for it. But I don't know what is the right code. I know that it will be in javascript. But I really don't know how...

like image 437
Akos Avatar asked Oct 01 '11 06:10

Akos


People also ask

How do I know if my scroll is at the top?

You can check if window. scrollY (the number of pixels the window has scrolled vertically) is equal to 0 . If you want to check if the window has been scrolled to its leftermost, you can check if window. scrollX (the number of pixels the window has scrolled horizontally) is equal to 0 .

How to check if scroll is at top jQuery?

Use jQuery to Detect if User has Scrolled to the Bottom or Top of a Page. $(window). scrollTop() – returns the current vertical position of the scroll bar. So if the scroll bar is at the very top, the value of $(window).

How do I know if my page is scrolled?

If you want to check whether the user has scrolled to the bottom of the page, you can use the scroll() jQuery event. The given code piece takes the top scroll of the window, so how much the page is scrolled down, it adds the height of the visible window and checks if it is equivalent to the height of the document.

How do you know if a page is fully loaded?

You can check the document. readyState property. From MDN: Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.


3 Answers

Elements have a scrollTop element that can be read or set. Make sure you're reading the correct element's scrollTop, the one that you're scrolling.

ex:

var div = document.getElementById('scrollable');
if(div.scrollTop==0){
    //Top of element
}
like image 67
mowwwalker Avatar answered Sep 23 '22 15:09

mowwwalker


Get the position of the scrollbar using this

function Getpostion(){    
    var vscroll = document.body.scrollTop;    
    alert(vscroll);
}

if vscroll is zero do your job. More details

like image 32
Irfan Avatar answered Sep 26 '22 15:09

Irfan


document.body.scrollTop === 0;
like image 20
marc carreras Avatar answered Sep 25 '22 15:09

marc carreras