11

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.

Quentin Engles
  • 2,744
  • 1
  • 20
  • 33
  • I created an ultra simple responsive gallery that uses **scrollLeft**. https://jsfiddle.net/swrkeg30/2/embedded/result/ **Interestingly** Firefox remembers the scrollposition on Hystory-Back. Chrome does not... at least in jsfiddle... I would bet this was working in chrome too, sadly I don't have the time right now to see what happened to Chrome - or if it's only fiddle's behavior in Chrome... – Roko C. Buljan Nov 14 '15 at 01:05
  • Back or no back - You can use scrollLeft/top as you please. Might not be accelerated as CSS3 `transition/animation` on `transform`, but it has it's simplistic use anyways. – Roko C. Buljan Nov 14 '15 at 01:08

1 Answers1

5

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)

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • 1
    Perfect! The history problem is not a deal breaker. As long as the scroll properties are consistent with overflow:hidden that's great. It is interesting though. I wonder if the history problem with chrome is a bug. I'm not familiar with the standards for that, and I'm not sure I want to look for it. :) – Quentin Engles Nov 17 '15 at 02:55
  • 1
    Do you have a plain javascript version? – chovy Oct 06 '18 at 01:38