开发者

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

开发者 https://www.devze.com 2023-04-10 02:13 出处:网络
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 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 i开发者_Go百科s 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...


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
}


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


document.body.scrollTop === 0;


To do the easy way: Include jquery library in your HTML document.

And to check if the user is on top of the page

var scrollPosition = $("body, html").scrollTop()
if (scrollPosition == 0){
   // top of the page
}


You would have to use javascript. Get to learn a little bit of jQuery.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号