<" /> <" /> <"/>

jQuery Slider - Moving Sliders at the same time

479 views Asked by At

I have three sliders as follows:-

<div class="slider" data-min="3800" data-max="30000" data-value="3848" data-step="500" data-target=".calc-deposit"></div>
<div class="slider" data-min="15400" data-max="120000" data-value="15393" data-step="2000" data-target=".calc-loan"></div> 
<div class="slider" data-min="57000" data-max="450000" data-value="57724" data-step="7500" data-target=".calc-mortgage"></div> 


$('.slider').each(function() {
    var $el = $(this);
    $el.slider({
        range: "max",
        min: $el.data('min'),
        max: $el.data('max'),
        value: $el.data('value'),
        step: $el.data('step'),
        slide: function(event, ui) {
            $($el.data('target')).html('£' + ui.value);

            // place code here which will execute when *any* slider moves
        }
    });
});

What I want to do is regardless of which slider you use, they all increase at the same time.

All three sliders have different increments so they need to update accordingly.

Any help would be much appreciated.

Example

2

There are 2 answers

0
BenG On BEST ANSWER

Here is one way using the stop and change event:-

$('.slider').each(function() {
  var $el = $(this);
  $el.slider({
    range: "max",
    min: $el.data('min'),
    max: $el.data('max'),
    value: $el.data('value'),
    step: $el.data('step'),
    stop: function(event, ui) {
      var percent = (100 / ($(this).data('max') - $(this).data('min'))) * $(this).slider('value');
      $('.slider').not(this).each(function() {
        $(this).slider('value', (($(this).data('max') - $(this).data('min')) / 100) * percent);
      });
    },
    change: function(event, ui) {
      $($el.data('target')).html('£' + ui.value);
    }
  });
});

FIDDLE

0
nsilva On

Based on BG101's answer, this is the final result:-

jQuery('.slider').each(function() {
    var $el = jQuery(this);
    $el.slider({
        range: "max",
        min: $el.data('min'),
        max: $el.data('max'),
        value: $el.data('value'),
        step: $el.data('step'),
        slide: function(event, ui) {
            var percent = (100 / (jQuery(this).data('max') - jQuery(this).data('min'))) * jQuery(this).slider('value');

            jQuery('.slider').not(this).each(function() {
                jQuery(this).slider(
                    'value', 
                    ((jQuery(this).data('max') - jQuery(this).data('min')) / 100) * percent
                );
            });
            jQuery('.slider').each(function() {
                var thisTarget = jQuery(this).data('target');
                var thisValue = jQuery(this).slider('option','value');

                jQuery(thisTarget+' span').html(thisValue);
            });

        },
    });
});

JSFIDDLE

(just thought I'd share)