Skip to content
Advertisement

How to create an event handler for a range slider?

I’m trying to get a range slider to work but I can’t. How do I add an event handler so when the user chooses a value my code reads that value. Right now its value is always 1.

I would like to do this using pure Javascript.

HTML:

<div id="slider">
    <input class="bar" type="range" id="rangeinput" min="1" max="25" value="1" onchange="rangevalue.value=value"/>
    <span class="highlight"></span>
    <output id="rangevalue">1</output>
</div>

JAVASCRIPT:

var rangeInput = document.getElementById("rangeinput").value;
var buttonInput = document.getElementById("btn");

if (buttonInput.addEventListener) {
    buttonInput.addEventListener("click", testtest, false);
}
else if (buttonInput.attachEvent) {
    buttonInput.attachEvent('onclick', testtest);
}

function testtest(e) {
    if (rangeInput > 0 && rangeInput < 5) {
        alert("First");
    } else {
        alert("Second");
    }
}

JSFIDDLE

Advertisement

Answer

Single Read

The problem is that you’re only reading the value once (at startup), instead of reading it every time the event occurs:

// this stores the value at startup (which is why you're always getting 1)
var rangeInput = document.getElementById("rangeinput").value;

You should be reading the value in the handler instead:

function testtest(e) {
    // read the value from the slider:
    var value = document.getElementById("rangeinput").value;
    // now compare:
    if (value > 0 && value < 5) {
        alert("First");
    } else {
        alert("Second");
    }
}

Or to rewrite your code:

var rangeInput = document.getElementById("rangeinput");
var buttonInput = document.getElementById("btn");

if (buttonInput.addEventListener) {
    buttonInput.addEventListener("click", testtest, false);
}
else if (buttonInput.attachEvent) {
    buttonInput.attachEvent('onclick', testtest);
}

function testtest(e) {
    var value = rangeInput.value;
    if (value > 0 && value < 5) {
        alert("First");
    } else {
        alert("Second");
    }
}

Updating rangevalue

It also looks like you want to update the output element with the value of the range. What you’re currently doing is referring to the element by id:

onchange="rangevalue.value=value"

However, as far as I know, this isn’t standard behavior; you can’t refer to elements by their id alone; you have to retrieve the element and then set the value via the DOM.

Might I suggest that you add a change listener via javascript:

rangeInput.addEventListener("change", function() {
    document.getElementById("rangevalue").textContent = rangeInput.value;
}, false);

Of course, you’ll have to update the code to use addEventListener or attachEvent depending on the browsers that you want to support; this is where JQuery really becomes helpful.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement