Advent of JavaScript, Day 6

Advent of JS Homepage

Challenge #6 is creating a Range Slider that updates a dollar amount:

Screenshot of slider

With the project files downloaded and codesandbox‘d into a live CodeSandbox, I’m ready to get going!


User Requirements

Again, let’s start with the User Requirements and speculate how I can solve these:

  • Move the knob on the range and the dollar amount above it will update.

That’s it. In their video, it goes from $0.00 to $100.00. Otherwise, it’s a standard <input type="range" />

Wiring it Up

change for inputs fire after the interaction is complete.

For live-updating values, input is the best event to listen for.

This is a very straightforward solution using .toLocaleString to handle the currency conversion for me:

const $dollars = document.querySelector('.dollars')
const $range = document.querySelector('#priceRange')

$range.addEventListener('input', (event) => {
  const { value } = event.target

  $dollars.innerHTML = (value / 100)
    .toLocaleString('en-US', {
      currency: 'USD',
      style: 'currency',
    })
    .slice(1) // Remove $
})

Demo

Easy-peasy!