Enable arrows in horizontal scroll

Asked

Viewed 375 times

1

I have a horizontal scroll, as I do to get the beginning and end of the scroll, I need to enable and disable the arrows.

function avancar() {
  document.getElementById('elementos').scrollLeft += 20;
}

function voltar() {
  document.getElementById('elementos').scrollLeft -= 20;
}
ul {
  width: 500px;
  border: solid 1px;
  overflow: hidden;
  overflow-x: auto;
  white-space: nowrap;
  padding: 0;
}

li {
  display: inline-block;
  width: 160px;
  text-align: center;
}

li:first-child {
  background: yellow;
}

li:last-child {
  background: red;
}

a {
  color: #333;
  text-decoration: none;
  margin: 20px;
}
<ul id="elementos">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
</ul>

<a href="#" onClick="voltar();">&lt; Voltar</a>
<a href="#" onClick="avancar();">Avançar &gt;</a>

1 answer

1


You gotta know three things:

  • the position of the scroll: el.scrollLeft
  • the width of the element: el.clientWidth
  • as much as you can scroll: el.scrollWidth

Once you’ve done that, the math is easy, and you can do it like this:

var el = document.getElementById('elementos');
var botoes = document.querySelectorAll('a');
var voltar = botoes[0];
var avancar = botoes[1];

function mover(direcao) {
  el.scrollLeft += 20 * direcao;
  var inicio = el.scrollLeft == 0;
  var fim = el.clientWidth + el.scrollLeft - el.scrollWidth;
  voltar.style.opacity = inicio ? 0 : 1;
  avancar.style.opacity = fim ? 1 : 0;
}
ul {
  width: 500px;
  border: solid 1px;
  overflow: hidden;
  overflow-x: auto;
  white-space: nowrap;
  padding: 0;
}

li {
  display: inline-block;
  width: 160px;
  text-align: center;
}

li:first-child {
  background: yellow;
}

li:last-child {
  background: red;
}

a {
  color: #333;
  text-decoration: none;
  margin: 20px;
  transition: opacity 0.5s;
}
<ul id="elementos">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
</ul>

<a href="#" onClick="mover(-1);" style="opacity: 0;">&lt; Voltar </a>
<a href="#" onClick="mover(1);">Avançar &gt;</a>

Browser other questions tagged

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