AppleTattooGuy AppleTattooGuy - 2 months ago 23
Javascript Question

jQuery UI Slider - have predefined 'pips'

I have a jQuery UI slider that goes in intervals of 100, I want to have some pips/lines under or over the slider at various intervals such as 100, 500, 1000, 2000 so when the user clicks these the slider will 'snap' straight to this value. Is this possible?

The code so far is:

jQuery( "#slider" ).slider({
value:2000,
min: 100,
max: 10000,
step: 100,
slide: function( event, ui ) {

jQuery( "#amount" ).val( ui.value );

},
stop: function( event, ui ) {

if( !$( "#age" ).val() ) {
alert("Please Enter Your Age");
jQuery( "#slider" ).slider("value", 2000);
jQuery( "#amount" ).val( $( "#slider" ).slider( "value" ) );
}

else if ( !$( "#name" ).val() ) {
alert("Please Enter Your Name");
jQuery( "#slider" ).slider("value", 2000);
jQuery( "#amount" ).val( $( "#slider" ).slider( "value" ) );
}

else if ( !$( "#email" ).val() ) {
alert("Please Enter Your Email");
jQuery( "#slider" ).slider("value", 2000);
jQuery( "#amount" ).val( $( "#slider" ).slider( "value" ) );
}

else {

jQuery( "#amount" ).val( ui.value );
jQuery( "p.loanSummary" ).text("Searching for loan amount €" + ui.value);

jQuery("button.compareLoans").show();
jQuery("p.toBorrow").show();

jQuery(".userData").fadeOut("slow");

jQuery.post(
MyAjax.ajaxurl,
{
action : "myajax-submit",
postID : MyAjax.postID,
postCommentNonce : MyAjax.postCommentNonce,
amount : $( "#slider" ).slider( "value" ),
age : $( "#age" ).val(),
},
function( response ) {
$("#content_update").html(response);
}
);

}

}
});

Answer

There is a library called noUiSlider which has the functionality you want. Here is an example, assuming you've downloaded the library and have the files in the same folder:

<head>
  <script src="https://code.jquery.com/jquery-2.1.1.js"></script>
  <script src="https://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
  <script src="nouislider.js"></script>

  <link rel="stylesheet" href="nouislider.css">
</head>

<div id="slider"></div>
<div id='slider-val'></div>
<script>
  var range_all_sliders = {
    'min': [     100 ],
    '5%': [   500 ],
    '10%': [   1000 ],
    '20%': [  2000 ],
    'max': [ 10000 ]
  };
  var pipsRange = document.getElementById('slider');
  noUiSlider.create(pipsRange, {
    range: range_all_sliders,
    start: 100,
    step: 1,
    pips: {
        mode: 'range',
        density: 4
    }
  });
  $('.noUi-value-large').on('click',function(){
    var val=parseInt($(this).text());
    pipsRange.noUiSlider.set(val);
  });
  pipsRange.noUiSlider.on('update', function( values, handle ) {
    $('#slider-val').html(values);
  });
</script>
Comments