According to MDN, the output element “represents the
result of a calculation or user action” typically used in forms. It has
been part of the HTML spec for quite some time. What
does it do? How does one use it? Let’s explore. We start by using it in
conjunction with a range slider:
<input type="range" name="quantity" id="quantity" min="0" max="100">
<output for="quantity"></output>Nothing much happens. By default output doesn’t have any
styles and doesn’t render anything in the browser. It also isn’t dynamic
so changing the value of the range yields no change in the output. A
trip to javascript is in order:
const rangeInput = document.querySelector( "input" );
rangeInput.addEventListener( "change", e => console.log( e.target.value ); );Now that should return the correct, current value of the
input element to the console. The next step is to select
the output element and change its value to that of the
input.
const output = document.querySelector( "output" );
rangeInput.addEventListener( "change", e => { output.value = e.target.value; });We have a number. Super. We should display the current number upon page load:
const setDefaultState = o => r => { o.value = r.value };
document.addEventListener( "DOMContentLoaded", () => {
setDefaultState( output )( rangeInput );
});At this point one can style-away to your hearts content. One more thing we can change is to use the input event-type rather than change to make a more robust solution:
rangeInput.addEventListener( "input", e => {
setDefaultState( output )( e.target );
});And there we have it. To try this out, copy and paste the code below into the console:
const setState = o => r => { o.value = r.value };
const output = document.createElement( "output" );
output.setAttribute( "for", "quantity" );
const range = document.createElement( "input" );
range.id = "quantity";
range.name = "quantity";
range.type = "range";
range.addEventListener( "input", e => {
setState( output )( e.target );
});
document.body.appendChild( range );
document.body.appendChild( output );
document.addEventListener( "DOMContentLoaded", () => {
setState( output )( range );
});