Home > Software engineering >  Prevent user scrolling but allow scrolling via JavaScript
Prevent user scrolling but allow scrolling via JavaScript

Time:10-23

I have a scrollable <div> and I need to prevent the user from scrolling. But at the same time, JavaScript should be allowed to scroll it.

Previously, I've tried setting overflow: hidden; but in some browsers/os it didn't let JavaScript scroll. I've tried setting overflow: auto; and hiding the scrollbar and then in JavaScript listening for wheel events and calling preventDefault() but that did nothing. I can't listen for scroll events because then it prevents JavaScript from scrolling too.

const btn = document.querySelector('button#scroll');
const cnt = document.querySelector('div#container');

btn.addEventListener('click', e => {
  cnt.scrollTo(20, 500);
});
div#container {
  width: 400px;
  height: 400px;
  overflow-y: auto;
  scroll-behavior: smooth;
  -ms-overflow-style: none;
  scrollbar-width: none;
}
div#container::-webkit-scrollbar {
  display: none;
}
<button id="scroll">Click to scroll</button>

<div id="container">
  <img src="https://p.turbosquid.com/ts-thumb/bK/x6a3nk/nlMteHHm/r1/jpg/1590782525/600x600/fit_q87/f469b1b09d4935ef73b0746eb4b77fbe06b57293/r1.jpg">
  <br>
  <img src="https://p.turbosquid.com/ts-thumb/bK/x6a3nk/nlMteHHm/r1/jpg/1590782525/600x600/fit_q87/f469b1b09d4935ef73b0746eb4b77fbe06b57293/r1.jpg">
  <br><img src="https://p.turbosquid.com/ts-thumb/bK/x6a3nk/nlMteHHm/r1/jpg/1590782525/600x600/fit_q87/f469b1b09d4935ef73b0746eb4b77fbe06b57293/r1.jpg">
  <br><img src="https://p.turbosquid.com/ts-thumb/bK/x6a3nk/nlMteHHm/r1/jpg/1590782525/600x600/fit_q87/f469b1b09d4935ef73b0746eb4b77fbe06b57293/r1.jpg">
  <br><img src="https://p.turbosquid.com/ts-thumb/bK/x6a3nk/nlMteHHm/r1/jpg/1590782525/600x600/fit_q87/f469b1b09d4935ef73b0746eb4b77fbe06b57293/r1.jpg">
  <br><img src="https://p.turbosquid.com/ts-thumb/bK/x6a3nk/nlMteHHm/r1/jpg/1590782525/600x600/fit_q87/f469b1b09d4935ef73b0746eb4b77fbe06b57293/r1.jpg">
  <br><img src="https://p.turbosquid.com/ts-thumb/bK/x6a3nk/nlMteHHm/r1/jpg/1590782525/600x600/fit_q87/f469b1b09d4935ef73b0746eb4b77fbe06b57293/r1.jpg">
  <br><img src="https://p.turbosquid.com/ts-thumb/bK/x6a3nk/nlMteHHm/r1/jpg/1590782525/600x600/fit_q87/f469b1b09d4935ef73b0746eb4b77fbe06b57293/r1.jpg">
  <br>
</div>

Any ideas? TYIA

CodePudding user response:

You can use overflow-y: hidden to make sure the scrolling position can only be changed by javascript.

CodePudding user response:

view-source:https://devforhelp.com/code2.html

Please open the link and check the source code

  • Related