Enable arrows in horizontal scroll

1

I have a horizontal scroll, how do I get the start 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>
    
asked by anonymous 08.06.2017 / 20:25

1 answer

1

You have to know 3 things:

  • scroll position: el.scrollLeft
  • element width: el.clientWidth
  • the maximum you can scroll: el.scrollWidth

With this the accounts are 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>
    
08.06.2017 / 20:44