ConnectedSliders

by russianpenguin

HTML

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/ui-lightness/jquery-ui.css">
<ul id="sliders">
</ul>
<button id="add">
Add new slider
</button>

CSS

#sliders {
    width: 200px;
}

#sliders li {
    margin-bottom: 10px;
}

#sliders div {
    margin-bottom: 5px;
}

JavaScript

var sliders = $("#sliders .slider");
const availableTotal = 100;
const template = '<li>\
        <span>\
          <div class="slider"></div>\
          <span class="value">0</span>\
        </span>\
        <a href="javascript:void(0)" class="remove">remove</span>\
    </li>';

function updateSliderList() {
	sliders = $("#sliders .slider");
  sliders.trigger("slide");
}

function updateSlider(event, ui) {
  // Update display to current value
  $(this).siblings().text(ui.value);

  // Get current total
  var total = 0;

  sliders.not(this).each(function() {
    total += $(this).slider("option", "value");
  });

  // Need to do this because apparently jQ UI
  // does not update value until this event completes
  total += ui.value;

  var max = availableTotal - total;

  // Update each slider
  sliders.not(this).each(function() {
    var t = $(this),
        value = t.slider("option", "value");

    t.slider("option", "max", max + value)
      .siblings().text(value + '/' + (max + value));
    t.slider('value', value);
  });
}

function configure() {
		updateSliderList();
    var value = parseInt($(this).text(), 10);

    $(this).empty().slider({
        value: 0,
        min: 0,
        max: 100,
        range: "max",
        step: 1,
        animate: 100,
        slide: updateSlider.bind(this)
    });
}

$(function(){
  $('#add').on('click', function() {
     var block = $(template).appendTo('#sliders');
     block.find('.slider').each(configure);
     block.find('.remove').on('click', function() {
      block.remove();
      updateSliderList();
     });
  })
})