Reputation: 173
I'm building a slider with a tooltip showing the updated value when the thumb is moved either by dragging or by clicking plus/minus button.
It works fine, but when I click plus/minus button AFTER dragging thumb it jumps to another position instead of continuing from where it is. How can I fix it to reflect the last value? Here's fiddle: https://jsfiddle.net/2q1rg56z/12/.
var update_num = $('output').text() * 1;
$('.plus').on('click', function() {
if (update_num < 100) {
$('output').text(++update_num);
$('input').val(update_num).trigger('input');
} else {
$('output').text(100);
}
});
$('.minus').on('click', function() {
if (update_num > 0) {
$('output').text(--update_num);
$('input').val(update_num).trigger('input');
} else {
$('output').text(0);
}
});
(It seems that the latest value should be stored in a var, so what should be the best way to do it?)
Upvotes: 1
Views: 77
Reputation: 58405
The problem is that this line only runs once:
var update_num = $('output').text() * 1;
You should turn it into a function
var update_num = function() { return +$('output').text(); };
Now call it in your code:
if (update_num() < 100) {
/***/
}
See this updated fiddle
Side Note: Note my use of +
to convert a string to an integer.See http://www.jstips.co/en/converting-to-number-fast-way/
Upvotes: 1
Reputation: 11317
You have almost given the answer yourself. Whenever the slider is used, you have to update the variable update_num
.
In your fiddle there is already the handler to do this:
$('.range-control > input').on('input', function() {
var value = this.value;
//...
So you only have to pull up your update_num
so you can access it from the scope of the slider input handler and set it the value
.
I updated the fiddle to make it work: https://jsfiddle.net/2q1rg56z/14/
Upvotes: 0