How to highlight the selected region in jquery slider? - javascript

I am using two jquery sliders, one with single and another multi handle. It's working okay but I need to show the selected range in a different colour and am unable to find the same in the documentation.
This is how my script looks like:
$(function() {
$( "#slider-1" ).slider({
slide: function(event, ui) {
$(this).css({
'background': 'rgb(107, 183, 185)'
});
}
});
});
This script does give the background color but to the full slider which is not what I want. I need to change the color for only the selected range.
This is how it looks with the current script:
This is what I am looking for:
And for the double handle range selector, this is the script from jquery UI that I am using:
$(function() {
$( "#slider-3" ).slider({
range:true,
min: 0,
max: 500,
values: [ 35, 200 ],
slide: function( event, ui ) {
$( "#price" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
}
});
$( "#price" ).val( "$" + $( "#slider-3" ).slider( "values", 0 ) +
" - $" + $( "#slider-3" ).slider( "values", 1 ) );
});
This one gives me the result as follows:
(I am unable to change the color here)

You have to do that manually, using some custom CSS.
Here is working snippet :
$(function() {
$("#slider-1").slider({
slide: changeRange
}).append('<div class="highlight"></div>');
});
$('#slider-1').click(changeRange);
function changeRange() {
let range = $(this).find('span').css("left");
$(this).find('.highlight').width(range);
}
.highlight {
background: teal;
height: 100%;
width: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="slider-1">
</div>
For double range slider, you just have to modify an element with CSS. Just add this to your css :
#slider-3 .ui-widget-header {
background: teal;
}

Related

Update global variable from jQuery event

Firstly, please note I am new to jQuery and have limited js experience, so this may be a silly question, but I have no one to ask for help.
I have a jQuery range slider which provides two year values. I have successfully created a variable which contains both the minimum and maximum year.
I am unsure how to update the min/max year variables after the user interacts with the range slider.
I need the the min/max year values as variables to use as a filter for a map/geojson query.
I have tried to declare the variable equal to ui.value(0) and ui.value[0], but that is as far as I have gotten. (example: yrmin = ui.value[0]; )
The only thing I know for certain is that I don't know enough. Any direction, comments, suggestions, or links to related exercises/ problems etc would be so incredibly helpful.
var yrmin = '';
var yrmax = '';
$( function() {
$( "#slider-range" ).slider({
range: true,
min: 1900,
max: 2020,
values: [ 1945, 1995 ],
slide: function( event, ui ) {
$( "#amount" ).val( " " + ui.values[ 0 ] + " - " + ui.values[ 1 ] );
}
});
$( "#amount" ).val( " " + $( "#slider-range" ).slider( "values", 0 ) +
" - " + $( "#slider-range" ).slider( "values", 1 ) );
yrmin = $("#slider-range").slider("values", 0);
yrmax = $("#slider-range").slider("values", 1);
});
When I use the the yrmin = ui.value(0); the console logs a ui not defined error..
You can use (window), but I do recommend to avoid the global approach as much as you can
window scope
window.yrmin = $("#slider-range").slider("values", 0);
window.yrmax = $("#slider-range").slider("values", 1);

How to multiply jQuery slider value by a defined variable?

I want to multiply the number of minutes per day, whose value is defined by the slider, by a specified number (like 0.05). Then I want to multiply that by 30 so that it is a rough monthly estimate. Then I want to display that value beside my "Estimated Monthly Bill" paragraph near the bottom.
Ex.
monthlyEstimate = slidervalue * .05 * 30
The slider is borrowed from the jQuery UI website. Here is the code:
<head>
<script>
$(function() {
$( "#slider-range-min" ).slider({
range: "min",
value: 1,
min: 1,
max: 150,
slide: function( event, ui ) {
$( "#amount" ).val( "" + ui.value );
}
});
$( "#amount" ).val( "" + $( "#slider-range-min" ).slider( "value" ) );
});
</script>
</head>
<body>
<style>
#slider-range-min{
width: 200px;
height:10px;
}
</style>
<div id="estimate">
<p>
<label for="amount">Minutes Per Day:</label>
<input type="text" id="amount" style="border: 0; color: #B01D63; font-family: Signika;" />
</p>
<div id="slider-range-min"></div>
<br />
<p>
Estimated Monthly Bill:
</p>
Add a span below your estimated monthly bill text so we can put the value in to a specified place:
HTML
<p>
Estimated Monthly Bill:
<span id="EstimatedMonthlyBill"></span>
</p>
Then change your slider slide property to do the calculation and insert the value:
Javascript
$(function() {
$("#slider-range-min").slider({
range: "min",
value: 1,
min: 1,
max: 150,
slide: function(event, ui) {
$("#amount").val("" + ui.value);
var estimatedMonthlyBill = Math.round(100 * (parseFloat(ui.value) * .05 * 30)) / 100;
$("#EstimatedMonthlyBill").text(estimatedMonthlyBill);
}
});
$("#amount").val("" + $("#slider-range-min").slider("value"));
});
Demo
http://jsfiddle.net/2FMRU/
Change
<p>
Estimated Monthly Bill:
</p>
To
<p>
Estimated Monthly Bill: <span id='estimate'></span>
</p>
We will use jQuery to up date the span named estimate when the slider is moved. * is the operator for multiplication in javascript. In the code below, replace SOME_CONSTANT to whatever you need it to be. Most decimal numbers eg. 100.234,0.00005 should work fine.
Change
slide: function( event, ui ) {
$( "#amount" ).val( "" + ui.value );
}
To something like this:
slide: function( event, ui ) {
$( "#amount" ).val( "" + ui.value );
$("#estimate").val("" + (ui.value*SOME_CONSTANT*30) );
}
When the slider is moved, the <span id='estimate'> will be updated to display the calculated value.
I hope this is what you were looking for.

Jquery UI slider how to make a box follow the handler?

I am trying to create a div that should follow the handler as it is seen here:
http://m1.dk/Priser/#tab:#calc,#abb
My JSfiddle: http://jsfiddle.net/z3xV3/2/
I also want to make a calculation on the UI value that should appear in the box.
Here is a illustration what I want to achieve:
HTML:
<div id="slider"></div>
<input id="sliderValue" />
Jquery:
$(document).ready(function() {
// Pris slider
$("#slider").slider({value:'',min: 0,max: 150,step: 1, range: 'min',
slide: function( event, ui ) {
$( "#amount" ).html( ui.value + ' timer');
}
});
$( "#amount" ).val( "$" + $( "#slider" ).slider( "value" ) );
});
I hope that's the effect you're looking for: http://jsfiddle.net/z3xV3/11/
JS
$(document).ready(function() {
$("#slider").slider({value:'', min: 0, max: 150, step: 1, range: 'min'});
var thumb = $($('#slider').children('.ui-slider-handle'));
setLabelPosition();
$('#slider').bind('slide', function () {
$('#sliderValue').val($('#slider').slider('value'));
setLabelPosition();
});
function setLabelPosition() {
var label = $('#sliderValue');
label.css('top', thumb.offset().top + label.outerHeight(true));
label.css('left', thumb.offset().left - (label.width() - thumb.width())/ 2);
}
});
HTML
<div id="slider"></div>
<input id="sliderValue" />
CSS
#sliderValue {
position:absolute;
width: 50px;
}
Best regards!
I have modifiered your jsfiddle example: http://jsfiddle.net/Dr5UR/
$("#amount").val("$" + $("#slider").slider({
slide: function(event, ui) {
$('#sliderValue').css('left', event.clientX).val(ui.value);
}
}));
I make use of the slide event of the slider.
The slide event got two arguments:
event
This object contains several informations about the event itself. The time of triggering, the key which has been pressed or the coordinates of the mouse at the moment of triggering. The clientX property contains the position we need to set to the moving object.
ui
The ui object comes from jQuery UI itself. It basicly just contains the value. Additionally it contains the anchor which is used for dragging too. But you can't use its position, cause the slide event takes effect before the anchor takes its new position.
The #slideValue input needs to have position: absolute;, cause I work with the left position attribute in CSS. You could also set the margin-left value, without need to set the position to absolute.
It's actually quite easy (and very useful) to turn this into a simple jQuery plugin. Like so:
JSFiddle: http://jsfiddle.net/PPvG/huYRL/
Note that I've added support for moving the slider by entering a value into the #sliderValue.
[ Code sample removed ]
You could also choose to remove #sliderValue from the HTML and let the plugin create it for you. In that case, you would rewrite the plugin so it would be called on the slider, instead of on #sliderValue. In my opinion, that would be a much neater solution.
Update
Based on your comments (and re-reading your question), I've rewritten the plugin example.
If I understand correctly, you want to do some calculations based on the value of the slider and display the result of those calculations in the label below the slider handle. The following should make that really easy.
JSFiddle: http://jsfiddle.net/PPvG/q5qg7/
HTML
<div id="slider"></div>
Plugin
(function($) {
$.fn.sliderLabel = function(options) {
var settings = $.extend({
marginTop: 2,
// Margin between the slider handle and the label (in pixels)
callback: function(value) {
return 'Value: ' + value;
}
}, options);
return this.each(function() { // <- maintains chainability
var slider = $(this);
var handle = slider.children('.ui-slider-handle');
var data = slider.data('sliderLabel');
if (handle.length === 0) {
// $(this) isn't a slider (it has no handle)
console.log('[SliderLabel] Error: sliderLabel() can only be called on a slider.');
return;
}
if (data === undefined) {
// First time sliderLabel() is called on this slider
data = {
label: $('<div class="ui-slider-label" />').css('position', 'absolute'),
callback: settings.callback
};
data.label.insertAfter(slider);
function updateLabel() {
var value = slider.slider('value');
var labelText = data.callback(value);
data.label.html(labelText);
data.label.css('top', handle.offset().top + handle.outerHeight() + settings.marginTop);
data.label.css('left', handle.offset().left - ((data.label.width() - handle.width()) / 2));
}
updateLabel();
slider.bind('slide', updateLabel);
} else {
// sliderLabel() was called before; just update the callback:
data.callback = settings.callback;
updateLabel();
}
// Save (or update) the data inside the slider:
slider.data('sliderLabel', data);
});
}
})(jQuery);
Usage
$("#slider").slider();
$("#slider").sliderLabel({
callback: function(value) {
return value + '%';
}
});
As you can see, the plugin is now called on the slider itself. You can now provide the plugin with a callback, which allows you to do some calculations and return a correctly formatted label (HTML is allowed).
In the example above, the callback simply takes the value that is passed to the callbackand appends '%'.
Here is a working example for a slider with two handles
$('#slider').slider({
range: true,
min: 500,
max: 10000,
step: 100,
values: [1000, 2000],
slide: function( event, ui ) {
$('#min-price').html('$' + ui.values[0]);
$('#min_budget').val(ui.values[0]);
$('#max-price').html('$' + ui.values[1]);
$('#max_budget').val(ui.values[1]);
}
//move labels when handles are moved
moveValueLabels();
}
});
//move the value labels directly under the handles
function moveValueLabels() {
var pos_first_handle = $('.ui-slider-handle:first').position();
var pos_last_handle = $('.ui-slider-handle:last').position();
$('#min-price').css('left', (pos_first_handle.left - ($('#min-price').width()/2)));
$('#max-price').css('left', (pos_last_handle.left - ($('#max-price').width()/2)));
}
//set initial positioning of labels when page is loaded
moveValueLabels();
CSS:
#slider {
overflow: visible;
#min-price {
position:absolute;
top:20px;
font-weight: bold;
padding:0;
}
#max-price {
position:absolute;
top:20px;
font-weight: bold;
padding:0;
}
}
HTML:
<div id="slider"></div>
CSS:
#slider {
width: 200px;
}
#sliderValue {
position: absolute;
left: 0;
bottom: -30px;
width: 40px;
}
jQuery:
$("#slider").slider({
value: '',
min: 0,
max: 100,
range: 'min',
create: function (event, ui) {
$('.ui-slider-handle').append('<input id="sliderValue" />');
},
slide: function (event, ui) {
$("#sliderValue").val(ui.value);
}
});
http://jsfiddle.net/yBfTy/4/
It would be nice to take a look at alternative solutions with jQuery plugins such as:
http://craigsworks.com/projects/qtip2/demos/#ui-slider
http://www.filamentgroup.com/lab/update_jquery_ui_slider_from_a_select_element_now_with_aria_support/
Taking your jsfiddle.
HTML:
<div id="slider"></div>
<input id="sliderValue" />
CSS:
#sliderValue{width:50px;}
Jquery:
$(document).ready(function() {
// Pris slider
$("#slider").slider({value:'',min: 0,max: 150,step: 1, range: 'min',
slide: function( event, ui ) {
$( "#sliderValue" ).val( ui.value + ' timer');
var offset = $(this).find('a').css("left");
$("#sliderValue").css("margin-left", offset);
}
});
$( "#sliderValue" ).val($( "#slider" ).slider( "value" ));
});
You can just: http://jsfiddle.net/z3xV3/21/
$(document).ready(function() {
$("#slider").slider({
value:0,
min: 0,
max: 150,
step: 1,
range: 'min',
slide: function( event, ui ) {
var offsetLeft = $(this).find(".ui-slider-handle").offset().left;
$( "#sliderValue" )
.val( ui.value + ' timer')
.css({
"position": "absolute",
"left": offsetLeft
});
}
});
});
The slide callback is called every time you move your handle:
offsetLeft is the offset of the handle.
$( "#sliderValue" ) is your input.

jQuery UI Slider: Range with 3 handles, and configurable colors?

I would like a jQuery UI slider that has five differently colored ranges defined by three handles. (So the first range would be handle 0 - handle 1, and the second range would be handle 1 to handle 2.) Is this possible through configuration, or must I hack it? If I have to modify the source, is there any guidelines for how to go about doing that?
Update: What I'm looking for in terms of ranges is:
| --- color 1 ----- handle1 --------- color 2 ------------- handle2 ------- color3 --------- handle3 -----color 4 ----|
(hopefully that makes sense.)
The range option defined in the jquery ui slider documentation does indeed limit the slider to only 2 handles. You need to create several elements when the slider raises the 'slide' or 'change' event and set the position of these manually, this way you can create a slider with multiple handles and multiple ranges which you can apply custom css to. See fiddle for a working example.
http://jsfiddle.net/AV3G3/3/
You probably want to use a range slider and pass in an array of 3 values to create 3 handles (according to the docs):
The slider widget will create handle
elements with the class
'ui-slider-handle' on initialization.
You can specify custom handle elements
by creating and appending the elements
and adding the 'ui-slider-handle'
class before init. It will only create
the number of handles needed to match
the length of value/values. For
example, if you specify 'values: [1,
5, 18]' and create one custom handle,
the plugin will create the other two.
If you don't insist on jQuery UI, noUiSlider can give ranges different classes and supports multiple handles - just as you ask. This example demonstrates how to color the ranges.
Modified with onclick reset,please find the complete code.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Slider functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<style>
.slide {
margin-top: 20px;
margin-left: 20px;
width: 400px;
background: red;
}
.slide-back {
position:absolute;
height:100%;
}
</style>
</head>
<body>
<!-- HTML -->
<button class="button">submit</button>
<p>
<label for = "price">Price range:</label>
<input type = "text" id = "price"
style = "border:0; color:#b9cd6d; font-weight:bold;">
</p>
<div id = "slider-3"></div>
</body>
<script>
var doUpdate = function(event, ui) {
$('#slider-3 .slide-back').remove();
$($('#slider-3 a').get().reverse()).each(function(i) {
var bg = '#fff';
if(i == 1) {
bg = 'red';
} else if(i == 2) {
bg = 'yellow';
} else if(i == 3) {
bg = 'green';
}
$('#slider-3').append($('<div></div>').addClass('slide-back').width($(this).offset().left - 5).css('background', bg));
});
};
$(".button").click(function(){
$('#slider-3').slider({
slide: doUpdate,
change: doUpdate,
min: 0,
max: 100,
values: [ 10, 30, 20],
slide: function( event, ui ) {
$( "#price" ).val( ui.values[ 2 ] );
}
});
$( "#price" ).val( $( "#slider-3" ).slider( "values", 0 )
);
doUpdate();
});
$('#slider-3').slider({
slide: doUpdate,
change: doUpdate,
min: 0,
max: 100,
values: [ 10, 30, 20],
slide: function( event, ui ) {
$( "#price" ).val( ui.values[ 2 ] );
}
});
$( "#price" ).val( $( "#slider-3" ).slider( "values", 0 ) );
doUpdate();
</script>
</html>

Parameterizing max value of a jQuery ui slider

I'm trying to create this slider
http://jqueryui.com/demos/slider/#rangemax
Is it possible to parametrize the max value?
For ex:
$("#slider-range-max").slider({
range: "max",
min: 1,
max: maxValue,
value: 2,
slide: function(event, ui) {
$("#amount").val(ui.value);
}
});
Is it possible to pass maxValue value, when I click on something? After its been initialized? Not on document ready function, but even after that?
You can set the values at any time, for max you'd do this:
$("#slider-range-max").slider("option", "max", newValue);
You can see how to do this with all the options at the jQuery UI site. Here's an example:
$(".increaseMax").click(function() {
var currentMax = $("#slider-range-max").slider("option", "max");
$("#slider-range-max").slider("option", "max", currentMax + 1);
});
According to the page you gave in your question (click on Options and then max):
Get or set the max option, after init.
//getter
var max = $( ".selector" ).slider( "option", "max" );
//setter
$( ".selector" ).slider( "option", "max", 7 );
Change 7 to any value/variable you want to set the new maximum value to.

Categories

Resources