4

I am using this custom JavaScript range slider, and I want to be able to get and set the sliders value. I already implemented the set function. (If you have a better way of doing it, please let me know.) I'm having trouble implementing the getValue function

I tried doing the following:

function getValue() {
    if (value) {
        return value;
    }
    return;
}

And when I call that function, I get the following error:

Uncaught ReferenceError: getValue is not defined

Creating a global variable, is not an option. How can I get the sliders value?

To set or get the sliders value, I want to be able to do the following:

mySlider.Value = 17;              // Set Value
var currentValue = mySlider.Value // Get Value

JSFiddle

function rangeSlider(elem, config, update) {

  if (typeof update != "undefined" && update) {
    var dragger = elem.getElementsByTagName('span')[0];
    var range = elem.getElementsByTagName('div')[0];
    var isVertical = config.vertical;
    var rangeWidth = range[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    var rangeOffset = range[!isVertical ? 'offsetLeft' : 'offsetTop'];
    var draggerWidth = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    dragger.style[!isVertical ? 'left' : 'top'] = (config.value / 100 * rangeWidth - (draggerWidth / 2)) + 'px';
    return;
  }

  function getValue() {
    if (value) {
      return value;
    }
    return;
  }

  var html = document.documentElement,
    range = document.createElement('div'),
    dragger = document.createElement('span'),
    down = false,
    rangeWidth, rangeOffset, draggerWidth, cachePosition;

  var defaults = {
    value: 0, // set default value on initiation from `0` to `100` (percentage based)
    vertical: false, // vertical or horizontal?
    rangeClass: "", // add extra custom class for the range slider track
    draggerClass: "", // add extra custom class for the range slider dragger
    drag: function(v) { /* console.log(v); */ } // function to return the range slider value into something
  };

  for (var i in defaults) {
    if (typeof config[i] == "undefined") config[i] = defaults[i];
  }

  function addEventTo(el, ev, fn) {
    if (el.addEventListener) {
      el.addEventListener(ev, fn, false);
    } else if (el.attachEvent) {
      el.attachEvent('on' + ev, fn);
    } else {
      el['on' + ev] = fn;
    }
  }

  var isVertical = config.vertical;

  elem.className = (elem.className + ' range-slider ' + (isVertical ? 'range-slider-vertical' : 'range-slider-horizontal')).replace(/^ +/, "");
  range.className = ('range-slider-track ' + config.rangeClass).replace(/ +$/, "");
  dragger.className = ('dragger ' + config.draggerClass).replace(/ +$/, "");

  addEventTo(range, "mousedown", function(e) {
    html.className = (html.className + ' no-select').replace(/^ +/, "");
    rangeWidth = range[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    rangeOffset = range[!isVertical ? 'offsetLeft' : 'offsetTop'];
    draggerWidth = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    down = true;
    updateDragger(e);
    return false;
  });

  addEventTo(document, "mousemove", function(e) {
    updateDragger(e);
  });

  addEventTo(document, "mouseup", function(e) {
    html.className = html.className.replace(/(^| )no-select( |$)/g, "");
    down = false;
  });

  addEventTo(window, "resize", function(e) {
    var woh = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    dragger.style[!isVertical ? 'left' : 'top'] = (((cachePosition / 100) * range[!isVertical ? 'offsetWidth' : 'offsetHeight']) - (woh / 2)) + 'px';
    down = false;
  });

  function updateDragger(e) {
    e = e || window.event;
    var pos = !isVertical ? e.pageX : e.pageY;
    if (!pos) {
      pos = !isVertical ? e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    if (down && pos >= rangeOffset && pos <= (rangeOffset + rangeWidth)) {
      dragger.style[!isVertical ? 'left' : 'top'] = (pos - rangeOffset - (draggerWidth / 2)) + 'px';
      cachePosition = Math.round(((pos - rangeOffset) / rangeWidth) * 100);
      config.drag(cachePosition);
    }
  }

  function initDragger() {
    var woh = dragger[!isVertical ? 'offsetWidth' : 'offsetHeight'];
    cachePosition = ((config.value / 100) * range[!isVertical ? 'offsetWidth' : 'offsetHeight']);
    dragger.style[!isVertical ? 'left' : 'top'] = (cachePosition - (woh / 2)) + 'px';
    config.drag(config.value);
  }

  range.appendChild(dragger);
  elem.appendChild(range);

  initDragger();

}

var slid1 = document.getElementById('range-slider-1');
var btn = document.getElementById('btn');
var anotherBtn = document.getElementById('anotherBtn');
var resultP = document.getElementById('results');

rangeSlider(slid1, {
  value: 10,
});
btn.onclick = function() {
  rangeSlider(slid1, {
    value: 50
  }, 1);
}

anotherBtn.onclick = function() {
  document.getElementById('results').innerHTML = "Your Current Value is: " + getValue();
}
.range-slider-track {
  height: 20px;
}
.range-slider-track:before {
  content: "";
  display: block;
  width: 100%;
  height: 2px;
  background-color: black;
}
.range-slider-track .dragger {
  display: block;
  width: 10px;
  height: inherit;
  position: relative;
  background-color: red;
}
<div id="range-slider-1"></div>
<button id="btn">Set Value</button>
<button id="anotherBtn">Get Value</button>
<p id="results"></p>

3
  • What is the variable value that getValue() returns supposed to be? I don't see it defined anywhere. Commented Dec 18, 2015 at 23:39
  • It's in the variable of defaults. (If you press 'ctr f' on chrome, you should be able to search for anything on that page.) Commented Dec 20, 2015 at 1:45
  • Then you have to reference it as defaults.value or from the config object (depending upon exactly what you're trying to do). You can't reference it as just value. Commented Dec 20, 2015 at 1:54

2 Answers 2

3

The function "rangeSlider()" should be handled as an object, not as a function...

You have to create an object:

var mySlider = new rangeSlider(slid1, { value: 10,});

And you can obtain its value as:

mySlider.getValue()

Take a look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! How can I assign the value like mySlider.value = 70?
You have a function for that in your code : mySlider.setValue(70) !
1

Paste this javascript into the original fiddle and sett it working:

function rangeSlider(elem, config, update) {
    var this_ = this;

    this.setValue = function(value) {
        var dragger = this.config.elem.getElementsByTagName('span')[0];
        var range = this.config.elem.getElementsByTagName('div')[0];
        var rangeWidth = range[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        var draggerWidth = dragger[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        dragger.style[!this.config.vertical ? 'left' : 'top'] = (value / 100 * rangeWidth - (draggerWidth / 2)) + 'px';
        this.config.value = value;
    };

    this.getValue = function() {
        return this.config.value;
    };

    var html = document.documentElement,
        range = document.createElement('div'),
        dragger = document.createElement('span'),
        down = false,
        rangeWidth, rangeOffset, draggerWidth, cachePosition;

    this.config = {
        value: (config.value || 0), // set default value on initiation from `0` to `100` (percentage based)
        vertical: (config.vertical || false), // vertical or horizontal?
        rangeClass: "", // add extra custom class for the range slider track
        draggerClass: "", // add extra custom class for the range slider dragger
        drag: function(v) { /* console.log(v); */ }, // function to return the range slider value into something
        elem: elem
    };

    addEventTo = function(el, ev, fn) {
        if (el.addEventListener) {
            el.addEventListener(ev, fn, false);
        } else if (el.attachEvent) {
            el.attachEvent('on' + ev, fn);
        } else {
            el['on' + ev] = fn;
        }
    }

    elem.className = (elem.className + ' range-slider ' + (this.config.vertical ? 'range-slider-vertical' : 'range-slider-horizontal')).replace(/^ +/, "");
    range.className = ('range-slider-track ' + config.rangeClass).replace(/ +$/, "");
    dragger.className = ('dragger ' + config.draggerClass).replace(/ +$/, "");

    addEventTo(range, "mousedown", function(e) {
        html.className = (html.className + ' no-select').replace(/^ +/, "");
        rangeWidth = range[!this_.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        rangeOffset = range[!this_.config.vertical ? 'offsetLeft' : 'offsetTop'];
        draggerWidth = dragger[!this_.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        down = true;
        updateDragger(e);
        return false;
    });

    addEventTo(document, "mousemove", function(e) {
        updateDragger(e);
    });

    addEventTo(document, "mouseup", function(e) {
        html.className = html.className.replace(/(^| )no-select( |$)/g, "");
        down = false;
    });

    addEventTo(window, "resize", function(e) {
        var woh = dragger[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        dragger.style[!this.config.vertical ? 'left' : 'top'] = (((cachePosition / 100) * range[!this.config.vertical ? 'offsetWidth' : 'offsetHeight']) - (woh / 2)) + 'px';
        down = false;
    });

    function updateDragger(e) {
        e = e || window.event;
        var pos = !this_.config.vertical ? e.pageX : e.pageY;
        if (!pos) {
            pos = !this_.config.vertical ? e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
        if (down && pos >= rangeOffset && pos <= (rangeOffset + rangeWidth)) {
            dragger.style[!this_.config.vertical ? 'left' : 'top'] = (pos - rangeOffset - (draggerWidth / 2)) + 'px';
            cachePosition = Math.round(((pos - rangeOffset) / rangeWidth) * 100);
            this_.config.value = cachePosition;
            this_.config.drag(cachePosition);
        }
    };

    this.initDragger = function() {
        var woh = dragger[!this.config.vertical ? 'offsetWidth' : 'offsetHeight'];
        cachePosition = ((config.value / 100) * range[!this.config.vertical ? 'offsetWidth' : 'offsetHeight']);
        dragger.style[!this.config.vertical ? 'left' : 'top'] = (cachePosition - (woh / 2)) + 'px';
        this.config.drag(this.config.value);
    };

    range.appendChild(dragger);
    elem.appendChild(range);

    this.initDragger();

}

var slid1 = document.getElementById('range-slider-1');
var btn = document.getElementById('btn');
var anotherBtn = document.getElementById('anotherBtn');
var resultP = document.getElementById('results');

var rs = new rangeSlider(slid1, {
    value: 10,
});

var slid2 = document.getElementById('range-slider-2');
var rs2 = new rangeSlider(slid2, {
    value: 20,
});


btn.onclick = function() {
    rs.setValue(50);
}
anotherBtn.onclick = function() {
    document.getElementById('results').innerHTML = "Range 1: " + rs.getValue() + '<br/>Range2: ' + rs2.getValue();
}

And this html also:

<div id="range-slider-1"></div>
<button id="btn">Set Value</button>
<button id="anotherBtn">Get Value</button>
<div id="range-slider-2"></div>
<p id="results"></p>

Like some of the other posters said, you need to fix your function a bit. I don't have time to clean up the new code, but I'm sure you'll get the idea. Here are a few things to keep in mind:

  1. You want to create a new object by calling new rangeSlider.
  2. You can assign the new object to a variable so you can use that variable to set or get values.
  3. Notice the var this_ = this statement so we'll have access to the object instance even certain events, because the this in those events may be the actual elements in the DOM.
  4. This new approach supports the multiple sliders in the document, as with your original code, but it is a lot more simpler and cleaner to get and set values.

I'm sure we can clean this code a lot more, so enjoy.

16 Comments

I copyd and pasted the code, and the slider doesn't show up.
Try this fiddle: jsfiddle.net/wvary/4c340taj/1 I copied the code and it works fine for me.
@Horay - That's because you did not set the drag function when you instantiate the object. currentThis.config = { value: (config.value || 0), // set default value on initiation from 0 to 100 (percentage based) vertical: (config.vertical || false), // vertical or horizontal? rangeClass: "", // add extra custom class for the range slider track draggerClass: "", // add extra custom class for the range slider dragger drag: (config.drag || function(v) { /* console.log(v); */ }), elem: elem };
@Horay - That's corret. Keep in mind when you use this method to set defaults on numerics. For example, if x is 0 and you execute x = (x || 54), then x is now 54. In that situation, you may want to perform x = (typeof x !== 'unddefined' ? x : 54).
config.value refers to the property value in the config object passed in by the second parameter when the object is instantiated, ie. new rangeSlider(a, b, c) <<< b is the config object. this_.config.value refers to value property of the config variable defined in the rangeSlider object.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.