Lewis Boyles-White
Lewis Boyles-White

Reputation: 141

Make HTML 5 range slider change based on value selected

I want to create a custom marker on HTML5 range.

The actual circle marker you drag I want to be able to change the design of this as they move and change the value. The example below moves from 1 through to 10. I want to change the colour as they change the value.

Any ideas?

<label for=weight>Party Scale</label>
<input type=range id=weight min=0 value=0 max=10 step=1>

Thanks,

Lewis

Upvotes: 1

Views: 3134

Answers (3)

Ga&#235;l Barbin
Ga&#235;l Barbin

Reputation: 3929

First, you have to reset the appearance of the input range, at least for webkit and gecko based browsers:

#myRange {
    -webkit-appearance: none;
}
#myRange::-moz-range-thumb{
    -moz-appearance: none;
}
#myRange::-webkit-slider-thumb {
    -webkit-appearance: none;
}

You have also to add some rules, because now the appearance of the element is not defined anymore (see the fiddle below)

then, you can listen for cursor moves with the input event, and add a css rule in a dynamicaly-created style sheet:

$("#myRange").on("input", function (evt) {
    if (evt.target.value > 50) 
        var rule= "background:red";
    else 
        var rule= "yellow"

    sheet.textContent = 
            "#myRange::-webkit-slider-thumb{ "+rule+" } " +
            "#myRange::-ms-thumb{ "+rule+" } " +
            "#myRange::-moz-range-thumb{  "+rule+" } ";

})

https://jsfiddle.net/rv9xqwq6/8/

some useful links:

http://brennaobrien.com/blog/2014/05/style-input-type-range-in-every-browser.html
http://codepen.io/thebabydino/pen/jEXjVE
http://trevan.co/custom-range-inputs-with-css-javascript/

Upvotes: 0

Bruffstar
Bruffstar

Reputation: 1289

HTML5 Ranges are limited. You are better using a plugin like noUiSlider, it has many more options, especially for what your trying to achieve.

Here is an example I made with it:

enter image description here

Demo Here

JS

var rangeSlider = document.getElementById('weight');

noUiSlider.create(rangeSlider, {
    start: [ 0 ],
    range: {
        'min': [  1 ],
        'max': [ 10 ]
    }
});

rangeSlider.noUiSlider.on('slide', function(values, handle){
    var v = values[handle],
        s = v * 10,
        l = 50;

    $(rangeSlider).find('.noUi-handle').css({"background-color":"hsl(10," + s + "%," + l +"%)"})
});

Upvotes: 1

tdebroc
tdebroc

Reputation: 1526

You can try adding:

 -webkit-appearance: none;

Then you can change

 background-color: blue;

A little example here: https://jsfiddle.net/rv9xqwq6/1/

Upvotes: 0

Related Questions