Reputation: 2460
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
Reputation: 10834
You can use scrollIntoView()
, it will scroll a specific item into view.
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
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
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