Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent scrolling due to overflow in non-scrollable elements

It's hard to explain the issue, as this seems more like a cross-browser bug than it does a feature. Follow the steps here to see the issue:

Steps to reproduce:

  1. Run code snippet.
  2. Click in textbox.
  3. Repeatedly press right-arrow key until text cursor passes edge of box.
  4. At this point the box will start 'scrolling' (in spite of the overflow: hidden). The grey background element that should fill the box 'slides' left, and to the right of it the white background behind can then be seen.

Desired behavior:

When going out of box, the text cursor simply escapes view, and the box scroll position does not slide to compensate.


How can I disable this 'no scrollbar' scrolling effect? (Note, it is in fact scrolling, because the js scrollLeft value of the overflow-box actually changes, even without a scrollbar.)

A CSS solution would really be ideal (e.g., a working overflow: hidden), but a Javascript solution could still suffice.

.overflow-box {
  margin: 20px;
  position: relative;
  width: 64px;
  height: 64px;
  overflow: hidden;
  border: 1px solid black;
}
.background {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #a0a0a0;
}
.textbox {
  position: relative;
  margin: 20px;
  width: 200px;
}
<div class="overflow-box">
  <div class="background"></div>
  <input type="text" value="aa bb cc dd ee ff gg hh ii jj kk ll mm nn oo" class="textbox"/>
</div>

I apologize if this question is a duplicate. I cannot find a similar question since I don't know what the effect is called..

TIA!

like image 665
Codesmith Avatar asked Oct 22 '25 20:10

Codesmith


1 Answers

Ok, so I discovered two things:

  1. The issue only occurs on elements with overflow: hidden
  2. When 'scrolling', the box emits the scroll event when changing, allowing one to do the following to prevent the scrolling:
document.querySelector('.overflow-box').addEventListener('scroll', evt => {
    evt.target.scrollTop = 0;
    evt.target.scrollLeft = 0;
});

Since I have a specific container that needs to prevent scroll, I'm using CSS to set overflow: hidden on it to trigger the issue on the container and not a parent element, and then I'm applying the JS above to prevent the scrolling.

This seems to be the best solution in my case.

If anyone knows of a simpler CSS solution, I will accept that answer over this one.

like image 135
Codesmith Avatar answered Oct 24 '25 11:10

Codesmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!