Window.onscroll

This article is in need of a technical review.

Summary

Specifies the function to be called when the window is scrolled.

Syntax

window.onscroll = funcRef;
  • funcRef is a reference to a function.

Examples

Example 1: Generic

window.onscroll = function (event) {
  // called when the window is scrolled.
}

Example 2: Detecting a scroll

The following example will launch an alert dialog whenever the page is scrolled.

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>onscroll test</title>
<script type="text/javascript">
window.onscroll = scroll;

function scroll () {
 alert("scroll event detected! " + window.pageXOffset + " " + window.pageYOffset);
 // note: you can use window.innerWidth and window.innerHeight to access the width and height of the viewing area
}
</script>
</head>

<body>
<p>Resize the window</p>
<p>to a very small size,</p>
<p>and use the scrollbars</p>
<p>to move around the page content</p>
<p>in the window.</p>
</body>
</html>

The following example will show a link to the top of the page whenever the vertical scroll exceeds 500 pixels.

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example</title>
<script type="text/javascript">
var appended = false, bookmark = document.createElement("div");
bookmark.id = "arrowUp";
bookmark.innerHTML = "<a href=\"#\" title=\"Top of the page.\">&uarr;<\/a>";
 
onscroll = function() {
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 500) {
    if (!appended) {
      document.body.appendChild(bookmark);
      appended = true;
    }
  } else {
    if (appended) {
      document.body.removeChild(bookmark);
      appended = false;
    }
  }
};
</script>
<style type="text/css">
#arrowUp {
  position: fixed;
  height: auto;
  width: auto;
  right: 10px;
  top: 10px;
  font-size: 48px;
}
#arrowUp a {
  text-decoration: none;
  color: black;
  font-weight: bold;
  font-family: serif;
}
</style>
</head>

<body>
<p>Page content here!</p>
</body>

</html>

Notes

bug 189308, in older versions of Gecko caused onscroll to be fired only when dragging the scroll bar, not when using cursor keys or mousewheel. This was fixed in Gecko 1.8/Firefox 1.5.

When the window.scrollX/scrollY isn't 0 -- meaning that some scrolling occurred by either script or manual action -- reloading the current page will trigger the onscroll event immediately.

Specification

Document Tags and Contributors

Last updated by: SamirTalwar,
Hide Sidebar