user2706762
user2706762

Reputation: 397

How to get page scrolling position (y axis)

How can i get the current scrolling position of my browser?, i want to fire events base on page position.This is what I tried:

var scroll_position=document.viewport.getScrollOffsets();

window.onscroll = function (event) {

if(scroll_position>1000)
{
alert('xxxxxxxxxxx');
}

Upvotes: 0

Views: 3434

Answers (3)

user2947761
user2947761

Reputation:

As hsz said, do

window.onscroll = function (event) {
var scroll_position = document.viewport.getScrollOffsets();
if (scroll_position > 1000)
{
    alert('xxxxxxxxxxx');
}
}

The problem with your code:

var scroll_position=document.viewport.getScrollOffsets();

scroll_position is only set once, when the page loads - therefore it stays the same (probably 0) and the alert never comes up because scroll_position is less than 1000.

hsz put the statement that sets scroll_position into the window.onscroll function, so it is updated every time the page scrolls.

Upvotes: 1

BenM
BenM

Reputation: 53246

Assuming that you're always going to be testing with window, you can use window.scrollY:

window.onscroll = function (event) 
{
    if(this.scrollY > 1000)
    {
        alert('xxxxxxxxxxx');
    }
}

jsFiddle Demo

Upvotes: 3

hsz
hsz

Reputation: 152294

Try with:

window.onscroll = function (event) {
  if (window.scrollY > 1000) {
    alert('xxxxxxxxxxx');
  }
}

Upvotes: 2

Related Questions