I have developed a volume controller in pure JavaScript. The mouse move works fine but unfortunately I am unable to make it a perfect volume controller. There are two issues facing on the function:
Volume not changing on mouse click
onmousemove
function keep on working even after onmouseup
var vControl = document.getElementById("voumecontrol");
var vNow = document.getElementById("volumenow");
var resultDiv = document.getElementById("result");
vControl.onmousedown = function (e) {
vControl.onmousemove = function (e) {
var varPosition = e.pageY - vControl.offsetTop;
var volPercentage = varPosition / vControl.offsetHeight;
kili = Math.abs((e.pageY - (vControl.offsetTop + vControl.offsetHeight)) / vControl.offsetHeight);
var volumePer = kili * 100;
vNow.style.height = volumePer + "%";
resultDiv.innerHTML = "volume position " + volumePer + "%";
}
vControl.onmouseup = function (e) {
vControl.onmousemove = function (e) {
e.preventDefault();
}
}
}
Volume is not changing on mouse click, because the function to be executed onmousemove
will only get executed when you move the mouse after clicking.
You should set onmousemove
to null
inside onmouseup
Here's the fixed version:
var vControl = document.getElementById("voumecontrol");
var vNow = document.getElementById("volumenow");
var resultDiv = document.getElementById("result");
var mousemovemethod = function (e) {
var varPosition = e.pageY - vControl.offsetTop;
var volPercentage = varPosition / vControl.offsetHeight;
kili = Math.abs((e.pageY - (vControl.offsetTop + vControl.offsetHeight)) / vControl.offsetHeight);
var volumePer = kili * 100;
vNow.style.height = volumePer + "%";
resultDiv.innerHTML = "volume position " + volumePer + "%";
}
vControl.onmousedown = function (e) {
mousemovemethod(e);
vControl.onmousemove = mousemovemethod;
vControl.onmouseup = function (e) {
vControl.onmousemove = null;
}
}
Updated Demo: http://codepen.io/anon/pen/iHaBe