Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is scrollTop, and scrollLeft for overflow hidden elements reliable?

I accidentally discovered that scrollTop, and scrollLeft on an element work even when an element is overflow: hidden. Can this behaviour be relied on?

Supposedly scrollTop, and scrollLeft are supposed to be zero for elements without scrollbars, and setting them on such elements is supposed to have no effect.

like image 502
Quentin Engles Avatar asked Nov 13 '15 23:11

Quentin Engles


1 Answers

Yes, even if an element has CSS overflow set to hidden,
Javascript Element.scrollTop(), Element.scrollLeft() allows you to manipulate the element's scroll position if the element contains overflowing children.

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

Here's a quick use case:

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

Not sure yet why Chrome does not do the following but:
Firefox will remember your gallery scroll-position on historyBack (navigating back to the page where you scrolled your gallery)

like image 193
Roko C. Buljan Avatar answered Oct 05 '22 06:10

Roko C. Buljan