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.
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.
transition/animation
on transform
, but it has it's simplistic use anyways.
– Roko C. Buljan
Commented
Nov 14, 2015 at 1:08
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/en-US/docs/Web/API/Element/scrollLeft
https://developer.mozilla/en-US/docs/Web/API/Element/scrollTop
Here's a quick use case:
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./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)
Can this behaviour be relied on?
it works for me in MSFT edge on my laptop ; on mobile , logs appear to say that scrollLeft
and scrollTop
in google chrome mobile are both 0
therefore , not always reliable