0

Here is my JS:

document.querySelector('input[type=range]').addEventListener('input', function(event) {
  console.log(event.target.value);
  console.log(window.location);

  document.querySelector('#day0' + event.target.value).scrollIntoView({
    behavior: 'smooth'
  });
});
<input type="range" min="0" max="100" value="7" step="1">

There are 100 items (labelled in #day000 format from #day001 to #day100). The slider will skip the first ten days when I slide to the right and when I slide all the way back to the left it will stop at day #009 or #010.

I'd like it to scroll all the way to the beginning. Any ideas?

Barmar
  • 741,623
  • 53
  • 500
  • 612
arw89
  • 107
  • 2
  • 11

2 Answers2

3

The problem is that you're not adding all the needed zeroes. When the slider value is 7, the selector will be #day07, not #day007.

It also won't work when the slider reaches the far right, because the selector will be #day0100 instead of #day100.

See How to output integers with leading zeros in JavaScript for how to pad a number with leading zeroes. Then you can use:

document.querySelector('#day' + pad(event.target.value, 3)).scrollIntoView({
    behavior: 'smooth'
});

or you could change your IDs to day0 through day100 instead of day000 throough day100.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I like using this style of padding numbers for javascript: `'#day' + ("000" + event.target.value).slice(-3)`. – Joseph Marikle Jun 01 '17 at 22:02
  • @JosephMarikle That's in one of the answers to the question I linked to. – Barmar Jun 01 '17 at 22:05
  • Yep, I know. I just wanted to highlight it. [This answer](https://stackoverflow.com/a/7254108/854246) uses that method (albeit with scientific notification), but even that one stuffs the code into a helper function, which OP may not need. Either way, the important part is the logic error of using `#day01` for a selector, which you pointed out. – Joseph Marikle Jun 01 '17 at 22:18
0

I see you have added a value property of 7 to your input, drop that or set it to zero and I think you're good to go

joostdelange
  • 113
  • 11