Change scrollbar positioning in a div

Asked

Viewed 290 times

2

By default, in a horizontal menu the content is read from left to right, as in this image: barra de rolagem à esquerda

However, I would like when the content is loaded, the scroll bar is, say, automatically moved to the right, as in this image: barra de rolagem à direita

This is possible?

3 answers

3

You can use flex-direction: row-reverse; to indicate that the order of the elements will start from brings forward, thus the scroll goes to the end of container. It’s enough you reorder the div to get to your liking.

See how it looks in the example:

.container {
  width: 500px;
  overflow-x: scroll;
  background-color: #ddd;
  display: flex;
  flex-wrap: nowrap;
  flex-direction: row-reverse;
}
.item {
  min-width: 150px;
  height: 50px;
  background-color: #f00;
  margin: 5px;
}
<div class="container">
  <div class="item">6</div>
  <div class="item">5</div>
  <div class="item">4</div>
  <div class="item">3</div>
  <div class="item">2</div>
  <div class="item">1</div>
</div>

  • I managed using the direction:rtl Thank you!

  • @Legal is an option too. Just remember that RTL means "right to left" is an orientation for screen readers to text that should be read from right to left as the Japones etc... so RTL would not be good by the semantic side of the thing. Mainly having other alternatives with both CSS and JS. But it’s still a solution :D

2

A more direct way to do this with javascript is:

var element = document.getElementById('ID-DO-ELEMENTO');
element.scrollTo(element.scrollWidth, 0);

2


If you are using jQuery, you can use the method scrollLeft(). An example:

$('.btn').on('click', function () {
  var $target = $('.content');
  $target.scrollLeft($target.outerWidth() + 20);
});
.content {
  border: solid 1px #000;
  padding: 1rem;
  max-width: 500px;
  overflow-x: auto;
  white-space: nowrap;
}

.btn {
  margin-top: 1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="content">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sit amet turpis lacus. Curabitur efficitur est mi, in fermentum arcu lobortis ut.
</div>

<button class="btn">Clique-me</button>

In your case, simply change the click event to when the page loads:

$(function () {
  var $target = $('seletor-do-elemento');
  $target.scrollLeft($target.outerWidth() + 20);
});

Reference:

  • Luiz Felipe, it worked too! I managed using the direction:rtl in pure CSS. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.