I have been trying to create 4 input type ranges which the sum of all those (4) have a sum of 100. For example:
Range 1 : 20%
Range 2 : 20%
Range 3 : 20%
Range 4 : 40%
If i drag the value of Range 4 to 50% i expect the below result:
Range 1 : 20%
Range 2 : 20%
Range 3 : 10% (last/previous range that was dragged)
Range 4 : 50%
The general concept :
I have an array which holds the id's of all type ranges. This array is being created on page load - so when the page loads the array looks like this :
["fitness-range","social-range","gourmet-range","street-range"]
Code :
var current_total_percentage = 0; // To have the total percentage
var slider_indexes = []; // The array which holds the id's of type ranges
// Loop each type range and add it's value to the total percentage
jQuery('input[type=range]').each(function (index, value) {
current_total_percentage += parseInt(jQuery(this).val());
slider_indexes.push(jQuery(this).attr("id")); // Add the id to the array
});
Everytime an input range is dragged i move it's ID to the first position of that array to know which range was dragged lastly => that means if another range is increased or decreased the lastly range should change value.
Function to move :
arraymove(slider_indexes, slider_indexes.indexOf(jQuery(this).attr("id")), 0);
function arraymove(arr, fromIndex, toIndex) {
var element = arr[fromIndex];
arr.splice(fromIndex, 1);
arr.splice(toIndex, 0, element);
}
I have tried a lot of things but it pretty challenging to make it work so any hints would be appreciated.
NOTES :
1) The step of the range value to be changed by 10. That means everytime a range's value is changed it goes +10 or -10.
2) When decreasing a range i want to decrease/increase the lastly dragged range by 10 in order to always have 100%.
3) If one range is dragged up to 100% all other ranges must become 0%, same row that appear that moment in array.
EDIT 1 : My solution until now -> https://jsfiddle.net/7q569ugo/10/ , it doesnt work if you drag the ranges too fast, or click on the lines of the ranges.
I think it would be easier for you to calculate the difference on the current slider and then apply that difference to the previous slider.
Then you have to handle if the previous slider is out of bounds (below 0 or over 100).
https://jsfiddle.net/htd8x2jz/1/
I'm afraid that's not the cleanest fail-to-the-next-slider solution, it should really be a method that loops through the array til it returns what slider should be updated. But the jsfiddle should be enough to get you on the way.
Personally I'd recommend all other sliders adjust when dragging one, the way you've described would make it very difficult to set them all to 25% for example. I appreciate that was not your question, but I thought I'd mention it.