GreenTriangle
GreenTriangle

Reputation: 2460

How can I control the horizontal scrolling of a div?

I have a div of fixed size that gradually adds more and more content, gaining a horizontal scrollbar. What I'd like is to be able to force the scrollbar all the way to the right whenever I want, so that I can keep the latest-added content always visible, driving older content off to the left. But without using jQuery -- which seems silly for one feature -- I can't seem to figure out a way to do this.

Upvotes: 2

Views: 5341

Answers (3)

Itay Gal
Itay Gal

Reputation: 10834

You can use scrollIntoView(), it will scroll a specific item into view.

here's an example

CSS

.cont{
  width: 200px;
  height: 100px;
  border: 1px solid black;
  overflow: auto;
  overflow-y: hidden;
  white-space: nowrap;
}

.element{
  width: 50px;
  margin: 10px;
  font-size: 40px;
  display: inline-block;
}

HTML

<div class="cont">
    <div class="element">1</div>
    <div class="element">2</div>
    <div class="element">3</div>
    <div class="element">4</div>
    <div class="element">5</div>
    <div class="element">6</div>
</div>

JavaScript

function scrollTo(item) {
    document.getElementsByClassName('element')[item].scrollIntoView();    
};

scrollTo(5);

Upvotes: 2

Vic
Vic

Reputation: 424

You could use the direction on parent controller and set it from right to left

div.container {
  width: 400px;
  height: 300px;
  overflow-x: scroll;
  direction: rtl;
}

div.scroller {
  width: 1000px;
  height: 300px;
}
<div class="container">
  <div class="scroller">

  </div>
</div>

make sure you wrap content in your scroller and set direction to ltr that should do what you need. Tested only in chrome on mac but rtl is what you need. If your container is dynamic its possible you will need to plonk some js like scrollIntoView(). It works with this static example.

Upvotes: 1

H77
H77

Reputation: 5967

Try setting the scrollLeft of the div to the scrollWidth.

e.g.

document.getElementById("btnAdd").onclick = function() {

  var divContent = document.getElementById("divContent");
  divContent.innerHTML += "<span>some stuff </span>";
  divContent.scrollLeft = divContent.scrollWidth;

};
#divContent {
  overflow-x: auto;
  overflow-y: hidden;
  height: 50px;
  width: 300px;
  white-space: nowrap;
}
<div id="divContent"></div>
<button id="btnAdd">add</button>

Upvotes: 1

Related Questions