Zuenie
Zuenie

Reputation: 973

Responsive slider javascript

I am trying to create a responsive slider. I have searched for many horizontal slider examples and found this one to be the most straight forward and simple. Now I want to adapt the code to make it responsive. When the slider is for example on 2013 than something should happen. All I need to know is where in the code I would implement this. So if anybody could help adapting underneath code that would be very helpful. Just a different print statement for each number that could be slided to would be awesome. Thank you in advance!

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Slider - Slider bound to select</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {
    var select = $( "#minbeds" );
    var slider = $( "<div id='slider'></div>" ).insertAfter( select ).slider({
      min: 1,
      max: 8,
      range: "min",
      value: select[ 0 ].selectedIndex + 1,
      slide: function( event, ui ) {
        select[ 0 ].selectedIndex = ui.value - 1;
      }
    });
    $( "#minbeds" ).change(function() {
       slider.slider( "value", this.selectedIndex + 1 );
    });
  });
   </script>
</head>
<body>

<form id="reservation">
   <label for="minbeds">Minimum number of beds</label>
   <select name="minbeds" id="minbeds">
    <option>2013</option>
    <option>2014</option>
    <option>2015</option>
    <option>2016</option>
    <option>2017</option>
    <option>2018</option>
    <option>2019</option>
    <option>2020</option>
   </select>
</form>


</body>
</html> 

Upvotes: 1

Views: 532

Answers (1)

This happens in the slide function

slide: function( event, ui ) {
    console.log(ui.value); // prints 1 for 2013, 2 for 2014 ...
    select[ 0 ].selectedIndex = ui.value - 1;
}

To make it responsive, use something like this

slide: function( event, ui ) {
    var index = ui.value-1;
    select[ 0 ].selectedIndex = index;
    if (select[0][index].text === "2013") { // text works, but innerHTML, innerText and label do too
        console.log("2013!");
    }
}

Upvotes: 1

Related Questions