patternjavascriptMinor
DRY multiple if statements used to show/hide elements based on slider value
Viewed 0 times
showelementsstatementsusedslidervaluemultipledrybasedhide
Problem
I'm showing and hiding 4 svg paths based on the value of a slider, all is working as expected, but it still feels a little cumbersome. Does anyone know a way to "DRY" it out a little more?
jsFiddle
jsFiddle
$('.volumeSlider').slider({
value: 1,
orientation: "vertical",
range: "min",
max: 1,
step: 0.05,
animate: true,
slide: function (e, ui) {
$('p').text(ui.value);
var v = $('.volume1');
if (ui.value == 1) {
v.show();
}
if (ui.value < 1) {
v.slice(0).hide();
v.slice(1, 4).show();
}
if (ui.value <= 0.65) {
v.slice(0, 2).hide();
v.slice(2, 4).show();
}
if (ui.value <= 0.35) {
v.slice(0, 3).hide();
v.slice(4).show();
}
if (ui.value === 0) {
v.hide();
}
}
});Solution
I am guessing that the '.volume' elements are like volume indicators, the louder the sound, the more you show.
You can iterate over the '.volume' elements, compare the
So, something like :
should work. This approach will work with any number of
I did not test this, but once you see/get this I am sure you can make this work.
Further optimizations can be caching
EDIT : I fixed the code to work with your HTML, the original was
which would work if the HTML elements were created in what I see as the correct order.
You can iterate over the '.volume' elements, compare the
index / elementCount to ui.value and decide to hide or show per that comparison.So, something like :
$('.volumeSlider').slider({
value: 1,
orientation: "vertical",
range: "min",
max: 1,
step: 0.05,
animate: true,
slide: function (e, ui) {
$('p').text(ui.value);
var v = $('.volume1');
for( var i = 0 ; i 1 / v.length * (i + 1)) ? v.slice(i).hide() : v.slice(i).show()
}
}
});should work. This approach will work with any number of
volume1 elements.I did not test this, but once you see/get this I am sure you can make this work.
Further optimizations can be caching
v.length and 1 / v.length, you could probably also use eq instead of slice()EDIT : I fixed the code to work with your HTML, the original was
( ui.value < 1 / v.length * (i + 1)) ? v.slice(i).hide() : v.slice(i).show()which would work if the HTML elements were created in what I see as the correct order.
Code Snippets
$('.volumeSlider').slider({
value: 1,
orientation: "vertical",
range: "min",
max: 1,
step: 0.05,
animate: true,
slide: function (e, ui) {
$('p').text(ui.value);
var v = $('.volume1');
for( var i = 0 ; i < v.length ; i++ ){
( 1-ui.value > 1 / v.length * (i + 1)) ? v.slice(i).hide() : v.slice(i).show()
}
}
});Context
StackExchange Code Review Q#39986, answer score: 4
Revisions (0)
No revisions yet.