Explain Codes LogoExplain Codes Logo

Onchange event on input type=range is not triggering in Firefox while dragging

html
event-handling
input-event
browser-compatibility
Anton ShumikhinbyAnton Shumikhin·Jan 18, 2025
TLDR

Quick fix: Switch to the input event to capture changes in real-time during the dragging of <input type="range">.

<input type="range" oninput="console.log(this.value);">

This ensures uniform behavior across all browsers, delivering live updates as the slider moves.

The event distinction: oninput vs onchange

In the HTML world, onchange and oninput events behave differently. onchange gets triggered when the input's value is committed by the user. On the other hand, oninput gives instant feedback when the value alters.

Specifically for <input type="range">, oninput captures real-time changes, while onchange waits for user's action completion, like releasing the slider.

Universal browser compatibility

Internet Explorer 10 (IE10) performs differently. Therefore, as a robust solution, incorporate both oninput and onchange events.

<input type="range" oninput="letTheFunBegin(this.value);" onchange="letTheFunBegin(this.value);">

Here, oninput offers smooth real-time updates, while onchange ensures the last man standing - the final value, doesn't get overlooked!

Enhancements: performance and accessibility

The oninput event is excellent for continuous updates, yet it can be a CPU hog due to its frequent triggering. To optimize and keep the animations silky, consider de-throttling the event or utilizing requestAnimationFrame. Moreover, remember its partner in crime, aria-valuenow to keep users of assistive technologies updated with the slider’s value.

Event firing behavior

When handling oninput, remember that this event might fire rapidly in quick succession, especially in Google Chrome. Therefore, ensure your event handlers can stand multiple hits and are effectively idempotent, or carry mechanisms to handle rapid-fire events.

Control enhancements with attributes

Go beyond defaults, use <input type="range"> element attributes like min, max, and step. They define a range, increments, and allow you to fine-tune the user experience with control.

Code structuring best practices

For better readability, always separate your JavaScript event handling functions from HTML file. This demarcation maintains a clean separation of concerns and makes event-related logic easilymanageable.

Solution validation: test, test, test

For a robust and universal solution, ensure cross-browser and mobile device compatibility testing. While the input event is broadly supported, testing helps to validate a consistent user experience across diverse platforms. Websites like "Can I use..." and "QuirksMode" come handy for checking browser support for web features.