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.
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.
Share Improve this question asked Jul 29, 2017 at 10:38 GreenTriangleGreenTriangle 2,4702 gold badges26 silver badges38 bronze badges 1-
What have you tried? Did you try to use
scrollIntoView()
– Itay Gal Commented Jul 29, 2017 at 10:43
3 Answers
Reset to default 2You 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);
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>
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.