Monday, August 3, 2009

Disable webpage scrolling using JavaScript

Sometimes you might want to disable scrolling on a webpage for certain reasons such as to display some pop-up div tag at fixed page center. Here is a simple CSS hack which can be used to disable the page scrolling very easily. The trick here is to use the CSS overflow property on document body as follows using JavaScript: = "hidden";

Using this trick alone would make the page scroll bars disappear but the page will be automatically scrolled to top-left corner. To fix this issue I have also included a hack to keep the page aligned to its current position when the scrolling is disabled. After the scrolling is disabled, it calculates the current page offsets and scrolls the window to current offsets to make it look as if it never moved.

Here are the JavaScript functions for disabling and enabling the page scrolling. You can trigger disablePageScroll() and enablePageScroll() functions from any DOM events:

<script type="text/javascript">
function disablePageScroll(){ = "hidden";
      setTimeout("scrollWindow(" + PageXoffset() + "," + PageYoffset() + ")", 0);
function enablePageScroll(){ = "auto";
      setTimeout("scrollWindow(" + PageXoffset() + "," + PageYoffset() + ")", 0);
function scrollWindow(X, Y) {
      window.scrollTo(X, Y);
function PageXoffset() {
      return window.pageXOffset ? window.pageXOffset : document[(document.compatMode == 'CSS1Compat') ? 'documentElement' : 'body'].scrollLeft;
function PageYoffset() {
      return window.pageYOffset ? window.pageYOffset : document[(document.compatMode == 'CSS1Compat') ? 'documentElement' : 'body'].scrollTop;

Technorati Tags:


Thanks a lot for your valuable comments :)