yash
yash

Reputation: 183

pure javascript method to set x scroll position in a div with overflow-x

How to set the x-position of scroll of a div with horizontal/overflow-x with pure javascript or angularjs ? Important: I'm not looking for jquery solutions - using angularjs,jquery wont work straightaway.

$anchorScroll() in angularjs scrolls to a vertical position but not to a horizontal position afaik. $window.scroll to or window.scrollTo(x,y) doesnt scroll within an overflow-x div. If anyone here is certail that methods I have tried would work under certain modifications, I would like to know as well.

Upvotes: 3

Views: 8598

Answers (2)

Ctojko
Ctojko

Reputation: 11

I stumbled on this wile i was looking for cross browser solution to this problem!
I figure it out that scrollBy on elements only works for Firefox!
I know it is an old question but maybe someone also look for this like me...
Lets say div id is scroll :

    function ScrollByLeft() {
          document.getElementById("scroll").scrollBy(10, 0);
    }
    function ScrollByRight() {
          document.getElementById("scroll").scrollBy(-10, 0);
    }

    function ScrollLeft() {
          document.getElementById("scroll").scrollLeft=10;
    }
    function ScrollRight() {
          document.getElementById("scroll").scrollLeft=-10;
    }
div#scroll {
	width: 180px;
	overflow-x: scroll;
}
<div id="scroll">
<p>
    Scroll.strange.wery.long.word.horizontally.for.10.pixels.left.and.right.also.but.only.on.Firefox.as.I.know</p>
</div>
<button onclick="ScrollByLeft()">ScrollBy Left!</button>
<button onclick="ScrollByRight()">ScrollBy Right!</button>
<br>
<button onclick="ScrollLeft()">ScrollLeft Left!</button>
<button onclick="ScrollRight()">ScrollLeft Right!</button>

Limitation:
ScrollBy works only on Firefox as I know...
Other browsers can only scroll window this way!
NOT other elements...

Upvotes: 1

chfumero
chfumero

Reputation: 1147

You can use $(selector).scrollLeft(amountToMove); on jQuery

document.getElementById(containerId).scrollLeft = amountToMove; using pure javascript or

angular.element(selector).scrollLeft(amountToMove); using angularjs.

Upvotes: 3

Related Questions