Gio Gio - 6 months ago 9
jQuery Question

How to effectively repeat jquery-ui function for multiple identifiers

I have the following javascript (jquery-ui library) function:

$(function() {
$("#mixerSlider0").slider({
orientation: "vertical",
range: "min",
min: 0,
max: 100,
value: 60,
slide: function(event, ui) {
$("#mixerInp0").val(ui.value);
}
});
$("#amount0").val($("#mixerInp0").slider("value"));
});


This function works perfect, and now I want to apply the same function for 64 more elements "mixerSliderX", "mixerInpX", and "amountX", where X=0..63.

Now I could simply copy paste this function 63 times, and adjust these identifiers, however I'm sure there's a more logical way to do this, and avoid such a terrible amount of code duplication. However I'm not sure how to go about this, hope somebody can help.

Answer

Give them all a class, e.g. class="mixerSlider", and a data attribute with the related input ID, data-input="mixerSlider0".

Also give your #amountX fields a class like .amount so you can operate on them as a group.

$(function() {
    $(".mixerSlider").slider({
        orientation: "vertical",
        range: "min",
        min: 0,
        max: 100,
        value: 60,
        slide: function(event, ui) {
            $('#' + $(this).data("input")).val(ui.value);
        }
    });
    $(".amount").val(function(i) {
        return $("#mixerInp" + i).slider("value");
    });
});