Languages
[Edit]
EN

JavaScript - stop page scroll with e.preventDefault()

4 points
Created by:
Root-ssh
177560

In this short article, we would like to show how to use e.preventDefault() to stop onscroll event with JavaScript.

Quick solution:

var handleScroll = function() {
    element.scrollTo(0, 0);  // required when scroll bar is drgged
};
    
element.addEventListener('scroll', handleScroll, false);
    
var handleEvent = function(e) {
    e.preventDefault();      // disables scrolling by mouse wheel and touch move
};
    
element.addEventListener('scroll', handleEvent, false);
element.addEventListener('mousewheel', handleEvent, false);
element.addEventListener('touchmove', handleEvent, false);

Note: go to this article to see pure CSS.

 

Practical example

Depending on what device we use, we need to handle scrolling occurred by mouse wheel, scrollbar dragging and touch moving.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    #container {
    	border: 1px solid red;
      	height: 200px;
      	overflow: auto;  /* prevents element content overflowing to outside */
    }
    
  </style>
</head>
<body>
  <div id="container">
    Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br />
    Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br />
    Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br />
    Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br />
    Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br />
    Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br /> Sime text...<br />
  </div>
  <script>

    var element = document.querySelector('#container');
    
    var handleScroll = function() {
      	element.scrollTo(0, 0);  // required when scroll bar is drgged
    };
    
    element.addEventListener('scroll', handleScroll, false);
    
    var handleEvent = function(e) {
    	e.preventDefault();      // disables scrolling by mouse wheel and touch move
    };
    
    element.addEventListener('scroll', handleEvent, false);
    element.addEventListener('mousewheel', handleEvent, false);
    element.addEventListener('touchmove', handleEvent, false);

  </script>
</body>
</html>

See also

  1. CSS - disable scroll bar 

Alternative titles

  1. JavaScript - disable scrollbar
  2. JavaScript - block scrollbar
  3. JavaScript - disable scrolling
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join