Languages
[Edit]
EN

JavaScript - stop page scroll with e.preventDefault()

3 points
Created by:
Root-ssh
115400

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 
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