jQuery UI Slider Missing BG - javascript

I'm using a range slider with jQuery UI but when I move the slider, the background line does not show up so it's hard to tell where it is at. How do I highlight the background line only for the selected portion?
jsfiddle is below.
https://jsfiddle.net/zbmt5qrn/
/* INTEREST RATE SLIDER */
$("#interestRange").slider({
min: 0,
max: 100,
step: 1,
values: [10],
slide: function(event, ui) {
for (var i = 0; i < ui.values.length; ++i) {
$("input.interestValue[data-index=" + i + "]").val(ui.values[i]);
}
}
});
$("input.interestValue").change(function() {
var $this = $(this);
$("#interestValue").slider("values", $this.data("index"), $this.val());
});
function handleInterestChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 24) input.value = 24;
}
var items =[ '8%','24%'];
var oneBig = 100 / (items.length - 1);
$.each(items, function(key,value){
var w = oneBig;
if(key === 0 || key === items.length-1)
w = oneBig/2;
$("#interestLabel").append("<label style='width: "+w+"%'>"+value+"</laben>");
});

I am removing the code about '8%/24%' because it does not seem to be relevant to this question.
There are a couple ways to set the background. You could insert a new element inside #interestRange and change its width based on the slider value. But if you do not need to worry about supporting outdated browsers, it would be much easier to use apply a linear-gradient to the background of #interestRange.
const sliderMin = 0
const sliderMax = 100
const sliderDefaultValue = 10
function setSliderBackground(value){
const sliderRange = sliderMax - sliderMin
const sliderPercent = Math.floor(100 * (value / sliderRange))
$("#interestRange").css({
background: `linear-gradient(90deg, #0000ff ${sliderPercent}%, #ffffff ${sliderPercent}%)`
})
}
function setSliderValue(value){
$("#interestRange").slider("value", value);
}
function setInputValue(value){
$("#interestValue").val(value)
}
$(document).ready(()=>{
$("#interestRange").slider({
min: sliderMin,
max: sliderMax,
step: 1,
// Handle when the user moves the slider
slide: (event, ui)=>{
const sliderValue = ui.value
setInputValue(sliderValue)
setSliderBackground(sliderValue)
}
})
// Handle when the user types in a value
$("#interestValue").change(()=>{
const typedValue = $("#interestValue").val()
setSliderValue(typedValue)
setSliderBackground(typedValue)
})
// Stuff to do when the page loads
setSliderValue(sliderDefaultValue)
setInputValue(sliderDefaultValue)
setSliderBackground(sliderDefaultValue)
})
<link href="https://code.jquery.com/ui/1.12.0-rc.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<p>Interest Rate:</p>
<div>
<div id="interestRange"></div>
<div id="interestLabel"></div>
</div>
<div>
<input type="number" id="interestValue" />
</div>

Related

noUIslider adjustment with plus and minus buttons on slider

Has anyone included anchor tags as a plus and minus function to increase and decrease your value on the slider of the noUIslider? I haven't found anything related to this using the noUIslider yet, but I'm in hopes someone has done it before. I have an example of one of my sliders when they're created below.
qdata['calc-rate'] = {value:4,type:"percent",decimals:3,post:"%",interface:"slider",min:0,max:10,inc:.125,label:'Interest Rate',display:''};
var f = qdata['calc-rate'];
var val = f['value'];
var sliderInterest = document.getElementById("paymentSliderInterest");
noUiSlider.create(sliderInterest, {
start:val,
behaviour:'tap',
range:{'min':0,'max':10},
connect:"lower",
step:f.inc,
format: wNumb({decimals: f.decimals})
});
sliderInterest.noUiSlider.on('slide', setInterestSliderDisplay);
There is "noUiSlider.get()" and "noUiSlider.set()" methods available to let you achieve this. I have done this for date and amount. Please have a look at code below and let me know if you have any question.
Please don't forget to have a look at stepSize variable in my script below. You can customise step size. In date you can select Year or Month. Hope this helpful to someone.
Simple number or amount
var connectSlider = document.getElementById('slider-connect');
noUiSlider.create(connectSlider, {
start: 100,
connect: [true, false],
range: {
'min': 0,
'max': 500
},
step : 1,
tooltips: wNumb({decimals: 0, suffix: 'K'}),
format: wNumb({decimals: 0})
});
connectSlider.noUiSlider.on('update', function (values, handle) {
document.getElementById('event-start').innerHTML = values[0] + "K";
//var myVal = connectSlider.noUiSlider.get();
});
function manualStep (direction){
var currentPosition = parseInt(connectSlider.noUiSlider.get());
var stepSize = 100;
if(direction == 'f'){
currentPosition += stepSize;
}
if(direction == 'b'){
currentPosition -= stepSize;
}
currentPosition = (Math.round(currentPosition / stepSize) * stepSize);
connectSlider.noUiSlider.set(currentPosition);
}
document.getElementById('stepforward').onclick = function() {manualStep("f")};
document.getElementById('stepback').onclick = function() {manualStep("b")};
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/12.0.0/nouislider.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/12.0.0/nouislider.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wnumb/1.1.0/wNumb.js"></script>
<p>
Some Amount
</p>
<div id="slider-connect"></div>
<div class="example-val" id="event-start">34</div>
<div class="example-val" id="event-end"></div>
<button id="stepback">Decrease</button>
<button id="stepforward">Increase</button>
Date Slider
// Create a new date from a string, return as a timestamp.
function timestamp(str) {
return new Date(str).getTime();
}
var dateSlider = document.getElementById('slider-date');
var dateNow = timestamp(Date.now());
noUiSlider.create(dateSlider, {
// Create two timestamps to define a range.
range: {
min: timestamp('2012'),
max: timestamp(dateNow)
},
// Steps of one week
step: 24 * 60 * 60 * 1000,
// Two more timestamps indicate the handle starting positions.
start: timestamp('2015'),
connect: [true, false],
tooltips: true,
// No decimals
format: { to: toFormat, from: Number }
});
function toFormat ( v ) {
return formatDate(new Date(v));
}
var dateValues = [
document.getElementById('event-start'),
document.getElementById('event-end')
];
dateSlider.noUiSlider.on('update', function (values, handle) {
dateValues[handle].innerHTML = values[handle];
});
// Create a string representation of the date.
function formatDate(date) {
// Create a list of day and month names.
var months = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
return months[date.getMonth()] + ", " +
date.getFullYear();
}
function manualStep (direction){
var currentPosition = dateSlider.noUiSlider.get();
var stepSize = 'month';
currentPosition = new Date(currentPosition);
if(stepSize === 'month'){
if(direction === 'f'){
currentPosition = new Date(currentPosition.setMonth(currentPosition.getMonth()+1));
}
if(direction === 'b'){
currentPosition = new Date(currentPosition.setMonth(currentPosition.getMonth()-1));
}
}
if(stepSize === 'year'){
if(direction === 'f'){
currentPosition = new Date(currentPosition.setFullYear(currentPosition.getFullYear()+1));
}
if(direction === 'b'){
currentPosition = new Date(currentPosition.setFullYear(currentPosition.getFullYear()-1));
}
}
dateSlider.noUiSlider.set(currentPosition);
}
document.getElementById('stepforward').onclick = function() {manualStep("f")};
document.getElementById('stepback').onclick = function() {manualStep("b")};
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/12.0.0/nouislider.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/12.0.0/nouislider.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wnumb/1.1.0/wNumb.js"></script>
<p>
Some date:
</p>
<div id="slider-date"></div>
<div class="example-val" id="event-start"></div>
<div class="example-val" id="event-end"></div>
<button id="stepback">Decrease</button>
<button id="stepforward">Increase</button>
JS Fiddle Link for Amount or Number
JS Fiddle Link for Date
You can use the keypress example from the documentation, but change the event from a keypress to a button click.
It uses the step option to get the next and previous step:
button.addEventListener('click', function( e ) {
var values = keypressSlider.noUiSlider.get();
var value = Number(values[handle]);
// [[handle0_down, handle0_up], [handle1_down, handle1_up]]
var steps = keypressSlider.noUiSlider.steps();
// [down, up]
var step = steps[handle];
// set slider
// ...
});
function incRateSlider(e){
// changes slider rate value using plus and minus buttons
if(e){ e.preventDefault(); }
var f = qdata['calc-rate'];
var id = $(this).attr("id");
var dir = 1;
if(id == "leftCircleRate"){ dir = -1; }
//console.log(f.value);
var newval = +f.value + +(dir * f.inc);// add or subtract values
if(newval > f.max){ newval = f.max;}
else if(newval < f.min){ newval = f.min; }
var slider = document.getElementById('paymentSliderInterest');
slider.noUiSlider.set(newval); //this sets the value for the slider "super necessary"
setInterestSliderDisplay(newval);
}
Since I had my own array of data set for the required pieces of 'calc-rate' it was able to use the 'f.inc' to increase or decrease based on the selected id to move the slider one step at a time. If there isn't enough clarity on how this works just let me know so I can edit more of it to make sense.

Change jquery animate to manually control function

I want to change jquery animate function, to a function which would let me control everything manualy. Currently code increases multiple numbers with delay. Here's the code (https://jsfiddle.net/6mrLv1ma/8/):
var ammount = 10;
var duration = 0.5;
var delay = (1-duration)/ammount; // 0.05
curDelay = 0;
for(var i=0;i<ammount;i++) {
$( "#container" ).append("<div id='output"+i+"'>0</div>");
setTimeout(
(function(i) {
return function() {
animate(i, duration);
}
})(i, duration),curDelay*1000);
curDelay += delay;
}
function animate(i, duration){
$({value: 0}).animate({value: 1}, {
duration: duration*1000,
step: function() {
var placement = "output"+i;
document.getElementById(placement).innerHTML = this.value;
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
Here's graph how it's working:
So if currentProc = 0.2, the output should be something like this:
0.3
0.16
0.07
0
0
0
0
0
0
0
I already started but need help with the formula(https://jsfiddle.net/18kd85hn/1/):
var ammount = 10;
var duration = 0.5;
var delay = (1-duration)/ammount; // 0.05
function myFunction(currentProc){ // currentProc value 0 - 1
var values = [];
for(var i = 0; i<ammount;i++){
var currentPos = i*delay; // formula
document.getElementById("output").innerHTML += "<br>"+currentPos;
}
}
myFunction(0.2)
<div id="output">output:</div>
Got it (https://jsfiddle.net/18kd85hn/7/)
var value = 1-(i*delay+duration-currentProc)/duration;
if (value<0){value =0}
if (value>1){value =1}
And replaced jquery animate - https://jsfiddle.net/18kd85hn/8/

How to get multiple sliders to work with java script/html/jquery

I'm currently working on a site that hosts podcasts. I have it so the podcasts plays, but I can only get very first podcast volume slider to work; the second podcast's sliders moves, but doesn't change the volume at all. Each player has a "player" id that is used to identify it. I've everything else and am stuck on this one little bug. Any help would be appreciated. Here is the javascript that creates the sliders and tries to links them to each player:
<script>
audiojs.events.ready(function()
{
var as = audiojs.createAll();
$('.slider').each(function()
{
var slider = $('.slider'),
tooltip = $('.tooltip'),
audioList = document.getElementsByTagName("audio").length;
console.log(audioList)
tooltip.hide();
slider.slider(
{
range: "min",
min: 0,
max: 100,
value: 50,
change: function()
{
for (var i = 0; i <= as.length; i++)
{
//console.log(i)
var value = $(".slider").slider("value");
document.getElementById("player").volume = (value / 100);
};
},
start:function(event,ui)
{
tooltip.fadeIn('fast');
},
slide: function(event, ui)
{
var volume = $('.volume'),
value = $(".slider").slider("value");
document.getElementById("player").volume = (value / 100);
tooltip.css('left',value / 2).text(ui.value);
if(value <= 5)
{
volume.css('background-position', '0 0');
}
else if (value <= 25)
{
volume.css('background-position', '0 -25px');
}
else if (value <= 75)
{
volume.css('background-position', '0 -50px');
}
else
{
volume.css('background-position', '0 -75px');
};
},
stop:function(event,ui)
{
tooltip.fadeOut('fast');
},});});}); </script>

jQuery UI Slider displays initial value on lowest setting

I have the following script for a jQuery UI slider. The script shows the amount in a div with id #skizzar_payment_amount
When I scroll to the lowest amount (0), the value in the div shows the initial amount instead of 0.
See here:
<script>
jQuery(function($) {
var initialValue = 7.5;
var maxValue = 20;
var stepValue = 0.25;
var sliderTooltip = function(event, ui) {
var curValue = ui.value || initialValue; // current value (when sliding) or initial value (at start)
var tooltip = '<div class="tooltip"><div class="tooltip-inner">£' + curValue + '</div><div class="tooltip-arrow"></div></div>';
$('.ui-slider-handle').html(tooltip); //attach tooltip to the slider handle
$("#skizzar_payment_amount").val(ui.value); //change amount in hidden input field
}
$("#slider").slider({
value: initialValue,
min: 0,
max: maxValue,
step: stepValue,
create: sliderTooltip,
slide: sliderTooltip,
});
$("#skizzar_payment_amount").val($("#slider").slider("value"));
});
</script>
https://jsfiddle.net/yzzvd52y/
ui.value will be 0, which is false in this line: var curValue = ui.value || initialValue;
Change it to e.g.:
var curValue = ui.value !== undefined ? ui.value : initialValue;
Updated fiddle
I updated your fiddle and added the following code:
change: function( event, ui ) {
$("#skizzar_payment_amount").val(ui.value);
}
Try this:
jQuery(function($) {
var initialValue = 7.5;
var maxValue = 20;
var stepValue = 0.25;
var sliderTooltip = function(event, ui) {
var curValue = ui.value >= 0 ? ui.value : initialValue; // current value (when sliding) or initial value (at start)
var tooltip = '<div class="tooltip"><div class="tooltip-inner">£' + curValue + '</div><div class="tooltip-arrow"></div></div>';
$('.ui-slider-handle').html(tooltip); //attach tooltip to the slider handle
$("#skizzar_payment_amount").val(ui.value); //change amount in hidden input field
}
$("#slider").slider({
value: initialValue,
min: 0,
max: maxValue,
step: stepValue,
create: sliderTooltip,
slide: sliderTooltip,
change: function(event, ui) {
$("#skizzar_payment_amount").val(ui.value);
}
});
});

Slide entire jQuery slider range

I have a multi-value jQuery slider with a defined step (it is defined by another slider, lets pretend for example's sake that it is a step:15) and a range of say 0-600. I want users to be able to drag the two values to the left and right like usual. But if a click is performed inside of the two values, they should be able to drag the whole range left and right.
A user is forced to set values like the following:
0,600
15,120
240,255
150,150
When, I want a user to be able to set values like the following:
1,271
15,165
25,115
580,595
These numbers still follow the step:15 rule of the slider, but can't be accessed with the basics of a jQuery slider because it wants to snap values to 30 increments (0,15,30,..,585,600). The most intuitive way I can think of this to be done is letting a user drag their 'range' of values left and right. But when the slider is clicked in between the two values, jQuery sets this as a new value.
I have used the slider's start event to detect if a user is clicking within the range (instead of clicking on a handle or the un-selected portion of the slider). I then need to set some sort of slide function within the slider that constantly detects the mouse position and slides left and right like that. I am at an intermediate level of Javascript (in my opinion) and not quite sure how I would go about doing that. You can play with my JSFiddle:
http://jsfiddle.net/JhKxh/9/
*note: the only problem with my JSFiddle is if you click the slider's border, it doesn't count as the class ui-slider-range (but some CSS tweaking should be able to fix this).
your answer should be here
Drag the Range of a UI Input Range Slider
Look here:
http://docs.jquery.com/UI/API/1.8/Slider
The following code works well and is an extension of your original jsfiddle. I finally understood what you wanted and it seems to work fine now:
Live Working Code Sample
JavaScript:
$(document).ready(function () {
'use strict';
var stepSlider = $('#stepSlider');
var stepText = $('#stepText');
var rangeSlider = $('#rangeSlider');
var rangeText = $('#rangeText');
var oldStep;
stepSlider.slider({
min:0,
max:120,
slide:function (event, ui) {
stepText.text(ui.value);
var rsValues = rangeSlider.slider("option", "values");
var stepDiff = ui.value - oldStep;
var rsMax = rangeSlider.slider("option", "max");
var rsMin = rangeSlider.slider("option", "min");
if (stepDiff > 0) {
rsValues[1] += stepDiff;
if (rsValues[1] > rsMax) {
rsValues[0] = rsMax - ui.value;
rsValues[1] = rsMax;
}
} else if (stepDiff < 0) {
rsValues[1] += stepDiff;
if (rsValues[1] < rsMin) {
rsValues[0] = rsMin;
rsValues[1] = ui.value;
}
}
rangeSlider.slider("option", "values", rsValues);
rangeText.text(rsValues[0] + ' - ' + rsValues[1]);
oldStep = ui.value;
}
});
rangeSlider.slider({
min:0,
max:600,
values:[0, 0],
slide:function (event, ui) {
var step = stepSlider.slider("option", "value");
var oldValues = rangeSlider.slider("option", "values");
var rsMax = rangeSlider.slider("option", "max");
var rsMin = rangeSlider.slider("option", "min");
var diff;
if (oldValues[0] != ui.values[0]) {
diff = ui.values[0] - oldValues[0];
if (diff > 0 && diff <= step && ui.values[1] === rsMax) {
return false;
}
ui.values[1] += diff;
if (ui.values[1] > rsMax) {
ui.values[1] = rsMax;
ui.values[0] = ui.values[1] - step;
}
rangeSlider.slider("option", "values", ui.values);
rangeText.text(ui.values[0] + ' - ' + ui.values[1]);
return false;
}
if (oldValues[1] != ui.values[1]) {
diff = ui.values[1] - oldValues[1];
if (diff < 0 && diff >= -step && ui.values[0] === rsMin) {
return false;
}
ui.values[0] += diff;
if (ui.values[0] < rsMin) {
ui.values[0] = rsMin;
ui.values[1] = ui.values[0] + step;
}
rangeSlider.slider("option", "values", ui.values);
rangeText.text(ui.values[0] + ' - ' + ui.values[1]);
return false;
}
rangeText.text(ui.values[0] + ' - ' + ui.values[1]);
}
});
oldStep = stepSlider.slider("option", "value");
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Sliders</title>
<link href="rangeSliders.css" rel="stylesheet" type="text/css"/>
<link href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
</head>
<body>
<div id="stepSlider">
<div id="stepText">0</div>
</div>
<div id="rangeSlider">
<div id="rangeText">0-600</div>
</div>
<script type="text/javascript" src="rangeSliders.js"></script>
</body>
</html>
CSS:
body {
margin: 50px;
}
#stepSlider, #rangeSlider {
width: 200px;
margin-bottom: 25px;
}
#stepText, #rangeText {
margin: -4px 0 0 225px;
width: 100%;
}

Categories