LCW
LCW

Reputation: 61

How can I build a div that displays the .scrollTop value of the body?

On my webpage I've got the following div:

<div style="position:fixed; z-index:100;"></div>

I'm trying to write a script that will return the current .scrollTop value of the body within the above div (e.g., if I'm scrolled 100px down the body, I would like the div to simply read: "100"), but I'm having a lot of trouble grasping .scrollTop and have no clue where to even start. Any help?

Upvotes: 0

Views: 97

Answers (2)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

You'll need a timing loop to continuously display the value:

<div id="a">0</div>

JS:

var showScroll = setInterval(function() {
     document.getElementById('a').innerHTML = (document.body.scrollTop)                                 
},50)

Upvotes: 2

nullability
nullability

Reputation: 10675

I'm assuming you're using jQuery here. You can bind a listener to the scroll event and have it replace the content of your div with the result of scrollTop(), like this:

var div = $("div"); //Replace this selector with an ID for your div
$(document).scroll(function() {
    div.html($(window).scrollTop());
});

Upvotes: 1

Related Questions