jqueryjquery-uijquery-slider

jQuery Multiple Slider action


I have 3 jQuery sliders on the same page:-

jQuery('.slider-deposit').slider({
    range: "max",
    min: 3800,
    max: 30000,
    value: 3848,
    step: 500,
    slide: function(event, ui) {            
        jQuery(".calc-deposit").html('£'+ui.value);
});

jQuery('.slider-loan').slider({
    range: "max",
    min: 15400,
    max: 120000,
    value: 15393,
    step: 2000,
    slide: function(event, ui) {
        jQuery(".calc-loan").html('£'+ui.value);
    }
});

jQuery('.slider-mortgage').slider({
    range: "max",
    min: 57000,
    max: 450000,
    value: 57724,
    step: 7500,
    slide: function(event, ui) {
        jQuery(".calc-mortgage").html('£'+ui.value);
    }
});

On change on ANY of the sliders I want to update a value on the page, how can this be achieved?

I did try:-

jQuery('.slider').slider({
    slide: function(event, ui) {            
        alert('test');
    }
});

But this doesn't work.


Solution

  • You can DRY up your code by using data attributes on the HTML element you instantiate the slider on. This will then allow you to run the same code on the slide event of all three. Try this:

    <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
            }
        });
    });
    

    Example fiddle