7
\$\begingroup\$

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

$('.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();
        }
    }
});
| improve this question | | | | |
\$\endgroup\$
4
\$\begingroup\$

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 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 < v.length ; i++ ){
            ( 1-ui.value > 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.

| improve this answer | | | | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.