Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with basic jQuery slider

As the title says, I'm trying to add a simple slider on an .html page.

This is my code:

$(document).ready(function() {
  // Slider
  $("#slider-range").slider({
    range: true,
    min: 0,
    max: 23,
    values: [0, 23],
    step: 1,
    slide: slideTime
  });
});

function slideTime(event, ui) {
  var val0 = $("#slider-range").slider("values", 0),
    val1 = $("#slider-range").slider("values", 1);
  var text = "";
  if (val0 < 12)
    text += val0 + "AM - ";
  else
    text += val0 + "PM - ";
  console.log(val0);
  console.log(val1);
  if (val1 < 12)
    text += val1 + "AM";
  else
    text += val1 + "PM";
  $("#time").text(text);
}

The problem that I'm facing is that the range should be from 0 to 23. However, when I use the slider, the lower bound goes from 1, to 0, to 1 again... As the upper bound seems to go from 22 to 23 to 22 again...

I'm not sure why this happens.

Here can be found an minimal example:

https://jsfiddle.net/7wft437c/

like image 347
pceccon Avatar asked Aug 05 '26 21:08

pceccon


2 Answers

Instead of

var val0 = $("#slider-range").slider("values", 0),
val1 = $("#slider-range").slider("values", 1);

Get the values in this way

var val0 = ui.values[0],
val1 = ui.values[1];

This is the Fiddle

like image 195
Baro Avatar answered Aug 08 '26 11:08

Baro


You need to change slide: slideTime to stop: slideTime.

slide gets the state before before the position changes, and your code is set up to evaluate where the slider is when the slide is done.

You can also call slideTime() after the slider is initialized so that it will label it before the user touches it:

$(document).ready(function() {
  // Slider
  $("#slider-range").slider({
    range: true,
    min: 0,
    max: 23,
    values: [0, 23],
    step: 1,
    stop: slideTime
  });
  slideTime();
});
like image 31
Tony Hinkle Avatar answered Aug 08 '26 10:08

Tony Hinkle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!