taufik-nurrohman / range-slider

The simplest JavaScript custom range slider ever!
MIT License
44 stars 11 forks source link

Programmatically set the value of the slider #1

Closed Horray closed 8 years ago

Horray commented 8 years ago

Hey there! I really like this simple and easy to use plug-in!! +1 For pure JavaScript!!

Is there a way to programmatically set the value of the slider after it was instantiated?

taufik-nurrohman commented 8 years ago

Yes. Take a look here → https://github.com/tovic/simple-custom-range-slider/blob/71f0cf4e206a869a1960009ca8969f5193042340/index.html#L73

Horray commented 8 years ago

Thanks for the answer! But I want to set the value after it is instantiated.

Horray commented 8 years ago

I want to do something like this:

mySlider.value = 18;

Also, I would like to get the sliders value like this:

var val = mySlider.value;

Thanks!

taufik-nurrohman commented 8 years ago

Too complicated for a simplest custom range slider. You can cache the slider value this way:

var mySlider = {
    value: 0
};

rangeSlider(elem, {
    drag: function(v) {
        mySlider.value = v; // cache the value to `mySlider`
    }
});

http://jsbin.com/jehudoxuha/edit?html,js,output

Horray commented 8 years ago

Thanks! How can I set the sliders value after it is instantiated?

Something like this:

mySlider.value = 18;
taufik-nurrohman commented 8 years ago

Not as variable but as method:

mySlider.setValue(18);

I’ve created a simple JavaScript class to enable your features:

Class

var RangeSlider = function(element, config) {
  var base = this;
  base.element = element;
  base.config = config;
  base.value = 0;
  // start ...
  base.init = function(v) {
    v = v || 0;
    base.value = v;
    base.config.value = v;
    rangeSlider(base.element, base.config);
  };
  // set value ...
  base.setValue = function(v) {
    base.element.innerHTML = ""; // reload content ...
    base.init(v);
  };
};

Usage

Initiation

var foo = new RangeSlider(document.querySelector('div'), { ... });

Start

foo.init(5); // set value to `5`

Update Value

foo.setValue(50); // update value to `50`

Get Value

alert(foo.value);

Demo: http://jsbin.com/xacaxo/edit?js,output