Is scrollTop and scrollLeft reliable overflow for hidden elements?

I accidentally discovered that scrollTop, and scrollLeftfor the elements work, even when the element overflow: hidden. Can you rely on this behavior?

Presumably scrollTop and scrollLeft should be zero for elements without scrollbars, and setting them on such elements should not have any effect.

+4
source share
1 answer

Yes , even if the CSS element overflowis mounted on a hidden,
Javascript is Element.scrollTop() , Element.scrollLeft()allows you to control the position of the scroll element , if the element contains child elements overflowing .

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

Here is a quick use case:

Animation Gallery Using scrollLeft

var GAL = $("#gal"),
    n = GAL.find(">*").length;
    c = 0;

$("button").on("click", function(){
  GAL.animate({ scrollLeft: (++c%n) * GAL.width() });
});
#gal {
  
  height:     40vh;
  overflow:   hidden; /* !! */
  white-space:nowrap;
  font-size:  0;
  
} #gal>* {
  
  font-size:      1rem;
  display:        inline-block;
  vertical-align: top;
  width:          100%;
  height:         inherit;
  background:     50% / cover;
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="gal">
  <div style="background-image:url(//placehold.it/800x600/cf5);"></div>
  <div style="background-image:url(//placehold.it/800x600/f0f);"></div>
  <div style="background-image:url(//placehold.it/800x600/444);"></div>
</div>

<button>scrollLeft</button>
Run codeHide result

Not sure why Chrome doesn't do the following:
Firefox will remember your gallery scroll position on historyBack (go to the page where you scroll through the gallery)

+2
source

Source: https://habr.com/ru/post/1615839/


All Articles