Question:
I got a request to create a range selection slider (integers 10-25) without resorting to the capabilities of jquery and third-party libraries. Only pure JS!.. well, a bit of hardcore. The question is – what is better – to resort to the option of creating two related inputs [type=range] or to study and do it using the Drag'n'Drop technology? And then the question is still about the first option, because. It seems to me that the second one is much more time-consuming:
how to prevent one of the sliders from moving towards the other after meeting the second one at a point?
Answer:
@MedvedevDev, Thank you for participating in yesterday's dialogue – today I made a slider using D'n'D – because. indeed, it looks more hackless in JS. If anyone needs the slider code: (I think, from the description you will understand which variable is responsible for which element):
var sliderElem = document.getElementById('range');
var thumbMin = document.getElementById('thumb-min');
var thumbMax = document.getElementById('thumb-max');
// var thumbMin = sliderElem.children[0];
var sliderCoords = getCoords(sliderElem);
var rangeEnd = sliderElem.offsetWidth - thumbMin.offsetWidth;
// var rangeEnd = sliderElem.offsetWidth;
var min = parseInt(getComputedStyle(thumbMin).left);
var max = parseInt(getComputedStyle(thumbMax).left);
console.log(parseInt(min), parseInt(max));
//минимум - 18, максимум - 48
thumbMin.onmousedown = function(e) {
var thumbCoords = getCoords(thumbMin);
var shiftX = e.pageX - thumbCoords.left;
document.onmousemove = function(e) {
var newLeft = e.pageX - shiftX - sliderCoords.left;
//если вне слайдера
if (newLeft < 0) {
newLeft = 0;
}
if (newLeft > max - thumbMin.offsetWidth / 2) {
newLeft = max - thumbMin.offsetWidth / 2;
}
min = newLeft;
thumbMin.style.left = newLeft + 'px';
}
document.onmouseup = function() {
console.log(getCoords(thumbMin));
console.log(min);
document.onmousemove = document.onmouseup = null;
}
return false;
};
thumbMax.onmousedown = function(e) {
var thumbCoords = getCoords(thumbMax);
var shiftX = e.pageX - thumbCoords.left;
document.onmousemove = function(e) {
var newLeft = e.pageX - shiftX - sliderCoords.left;
//если вне слайдера
if (newLeft < min + thumbMin.offsetWidth / 2) {
newLeft = min + thumbMin.offsetWidth / 2;
}
if (newLeft > rangeEnd) {
newLeft = rangeEnd;
}
max = newLeft;
thumbMax.style.left = newLeft + 'px';
}
document.onmouseup = function() {
console.log(getCoords(thumbMax));
console.log(max);
document.onmousemove = document.onmouseup = null;
}
return false;
};
thumbMin.ondragstart = function() {
return false;
};
function getCoords(elem) {
var box = elem.getBoundingClientRect();
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset
};
}