Situation: there is a fixed-height parent div with overflow: auto
and enough child "line-item" divs of sufficient height to trigger the presence of scrollbars. Each of these child divs has tabindex=-1 so can be programmatically focused.
When any of these child divs is programmatically focused, the default behavior of the browser (in this case, Chrome 55) seems to be to scroll the parent div to center the newly-focused child. Is there any way to prevent this behavior?
And it is simply by adding the CSS property overflow: hidden; on the element you want to prevent the scroll.
To do this (in Chrome, Firefox, and Edge), we can add the CSS property overscroll-behavior: contain to the overflow: auto element. This will prevent the "scroll chaining" behavior, which will, in turn, keep the mouse-wheel active within the target element.
mouseleave(function() { $('body'). bind('mousewheel DOMMouseScroll', function() { return true; }); }); This is stopping all scrolling where as I want scrolling to still be possible inside the container.
Yes and no. There is not a way to prevent the parent element from scrolling to the focused element (that I know of). However, you can undo the scrolling by scrolling the parent element back to the top. Done correctly, it won't be noticeable to the user.
To do this, anytime you programmatically focus an element, retrieve the current scroll offset of the focused element's parent node and set scrollTop
to that offset.
var children = document.getElementsByClassName('child')
for (var i = 0; i < children.length; i++) {
children[i].addEventListener('click', function (e) {
e.preventDefault
var focused = document.getElementById('focus')
var focusedParent = focused.parentNode
var savedOffset = focusedParent.scrollTop
focused.focus();
focused.parentNode.scrollTop = savedOffset;
})
}
.parent {
height: 300px;
overflow: auto;
}
.child {
height: 50px;
background-color: gray;
border-bottom: 1px solid black;
color: white;
box-sizing: border-box;
text-align: center;
line-height: 50px;
font-family: Arial;
}
<div class="parent">
<div class="child" tabIndex="-1">1</div>
<div class="child" tabIndex="-1">2</div>
<div class="child" tabIndex="-1">3</div>
<div class="child" tabIndex="-1">4</div>
<div class="child" tabIndex="-1">5</div>
<div class="child" tabIndex="-1">6</div>
<div class="child" tabIndex="-1">7</div>
<div class="child" tabIndex="-1">8</div>
<div class="child" tabIndex="-1" id="focus">9</div>
<div class="child" tabIndex="-1">10</div>
</div>
Here's the working demo on Codepen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With