The purpose of this tutorial is to guide you on how to implement range sliders for numeric input in your web projects.
By the end of this tutorial, you will be able to create an HTML range slider, style it using CSS, and manipulate its values with JavaScript.
Basic knowledge of HTML, CSS, and JavaScript is required.
The HTML <input type="range">
defines a control for inputting a number whose exact value is not important. This is often used in the case of data that falls within a set range of values, like volume or brightness control.
The appearance of the range slider can be improved with CSS. The properties used to style sliders vary slightly between browsers.
You can use JavaScript to interact with the slider, read its current value, or change the value programmatically.
Here's how to create a basic slider that goes from 0 to 100.
<input type="range" min="0" max="100" value="50" id="myRange">
In this code snippet:
- type="range"
creates the range slider.
- min="0"
and max="100"
set the minimum and maximum values for the slider.
- value="50"
sets the initial value for the slider.
- id="myRange"
is used to identify the slider in our JavaScript code.
Now let's add some style. Note that the styling properties can differ between browsers.
input[type=range] {
width: 100%;
height: 25px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
transition: opacity .2s;
}
input[type=range]:hover {
opacity: 1;
}
In this code snippet:
- We select the range input with input[type=range]
.
- width: 100%
makes the slider take up the full width of its container.
- height: 25px
sets a fixed height.
- background: #d3d3d3
sets a gray background color.
- outline: none
removes the default browser outline.
- The opacity
and transition
properties add a simple hover effect.
Finally, let's use JavaScript to display the current value of the slider.
var slider = document.getElementById("myRange");
var output = document.getElementById("value");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
In this code snippet:
- We get a reference to our slider with document.getElementById("myRange")
.
- We also get a reference to an element where we'll display the value.
- We then set the initial value with output.innerHTML = slider.value
.
- Whenever the slider's value changes (slider.oninput
), we update the displayed value.
In this tutorial, we've covered how to create a range slider with HTML, style it with CSS, and interact with it using JavaScript.
Remember to practice, experiment with different values, styles, and try to create more complex interactions. Explore the MDN Web Docs for more detailed information about <input type="range">
, CSS styling, and JavaScript interactivity.