Determine click position on progress bar?

bobbyrne01 picture bobbyrne01 · Feb 4, 2015 · Viewed 15.3k times · Source

Is it possible to determine the value/position of a user's click on a progress bar using plain javascript?

Currently, I can detect a click on the element but can only get the current position of the bar, not related to the user's click.

http://jsfiddle.net/bobbyrne01/r9pm5Lzw/

HTML

<progress id="progressBar" value="0.5" max="1"></progress>

JS

document.getElementById('progressBar').addEventListener('click', function () {
    alert('Current position: ' + document.getElementById('progressBar').position);
    alert('Current value: ' + document.getElementById('progressBar').value);
});

Answer

Josh Crozier picture Josh Crozier · Feb 4, 2015

You can get the coordinates of where you clicked inside of the element like this:

Just subtract the offset position of the element from the coordinate of where the page was clicked.

Updated Example

document.getElementById('progressBar').addEventListener('click', function (e) {
    var x = e.pageX - this.offsetLeft, // or e.offsetX (less support, though)
        y = e.pageY - this.offsetTop,  // or e.offsetY
        clickedValue = x * this.max / this.offsetWidth;

    console.log(x, y);
});

If you want to determine whether the click event occurred within the value range, you would have to compare the clicked value (in relation to the element's width), with the the value attribute set on the progress element:

Example Here

document.getElementById('progressBar').addEventListener('click', function (e) {
    var x = e.pageX - this.offsetLeft, // or e.offsetX (less support, though)
        y = e.pageY - this.offsetTop,  // or e.offsetY
        clickedValue = x * this.max / this.offsetWidth,
        isClicked = clickedValue <= this.value;
    
    if (isClicked) {
        alert('You clicked within the value range at: ' + clickedValue);
    }
});
<p>Click within the grey range</p>
<progress id="progressBar" value="5" max="10"></progress>