Skip to content

USWDS - Feature: [Update the Range slider aria-valuenow attribute in real time when the slider is changed by a user] #5038

@danny-englander

Description

@danny-englander

Is your feature request related to a problem? Please describe.

I noticed that when using the Range Slider component, https://designsystem.digital.gov/components/range-slider/, the aria-valuenow attribute does not update in real time as a user changes the position of the slider. In addition, there should be an initial value set that I would think would be the average of the min and max values.

Describe the solution you'd like

Here is code that sets a basic average starting value and then updates in real time as the user changes the slider position.

      // Calc avg / mean function.
      function calcAverage(array) {
        return (
          array.reduce(
            (previousValue, currentValue) => previousValue + currentValue
          ) / array.length
        );
      }

      // Query all usa-range items.
      const form_ranges = document.querySelectorAll('.usa-range');

      if (form_ranges) {
        // Array reduce for the above, there could be more than one on a page.
        const form_range_item = [...form_ranges];
        // Loop all range sliders.
        form_range_item.forEach((range_item) => {

          // Define min / max and calc mean with the function.
          // Use Math.trunc to convert the "number" from a string to a number.
          const min = Math.trunc(range_item.getAttribute('min'));
          const max = Math.trunc(range_item.getAttribute('max'));
          const range_start_value = (calcAverage([min, max]))

          // Set the starting value when the page loads
          // as the mean between min and max.
          range_item.setAttribute('aria-valuenow', range_start_value)

          // Listen for a change on the slider and update it in real time.
          range_item.addEventListener("change", function () {
            this.setAttribute("aria-valuenow", this.value)
          })
        });
      }

Describe alternatives you've considered

None at this time

Additional context

No response

Code of Conduct

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions