You might assume that a big fan of HTML5 such as myself would use the range input field to implement the slider. You would be wrong. Unfortunately, I do try to keep the comic mostly compatible with IE9 (that might change be the end of the year) and it does not support the range type of input. Also, the default styling of the range slider looks pretty terrible. It would have taken me a while to get something that looked the way I wanted.
A standard HTML5 slider control. Input type "range" does this. |
The jQuery Mobile Slider control. Looks nice, destroys Amphibian.com. |
Start by including the bootstrap-slider.js (or bootstrap-slider.min.js) file on your page. Also include the bootstrap-slider.css (or bootstrap-slider.min.css). Then write some HTML like this:
<input id="brightnessSlider" type="text" data-slider-tooltip="hide" data-slider-id="bSlider" data-slider-min="0" data-slider-max="19" data-slider-step="1" data-slider-value="19"/>
Note that the type of the input is "text" and not "range." Don't worry about that for now, look at the data-slider- attributes. These are used to pass configuration settings to the control. In my case, I wanted to hide the tooltip, set the minimum value to 0, the maximum value to 19 (for 20 total values), the stepping to 1, and start with a value of 19 (the max). The data-slider-id attribute is of interest, though. What it means is that when the JavaScript turns this input into a bunch of other elements that look like a slider, the parent div for all those will be named "bSlider". Once that's created, this text input will be hidden from view. But when the user interacts with the slider, the value will be written back to the text input's value - making it easy to figure out what to use when the form is submitted.
Take a look at the JavaScript now.
var bChange = function() { var n = Number($('#brightnessSlider').val()); console.log("current value is " + n); }; var bslide = $('#brightnessSlider').slider() .on('change', bChange);
In this example, the bChange function doesn't really do much, but it shows how you can get the current value of the slider. The bChange function is passed in as the event handler for the change even when the slider is created.
If you want to change the width of the slider, the only way I found was to alter the CSS width attribute of the control's created div. I did this programmatically when the comic is displayed in one of the small-screen formats. Remember, the control's div will have the id matching the data-slider-id attribute in the input tag.
$("#bSlider").css("width", "150px");
The default width seemed to be 210px, but I reduced that to 150px for the phone screen sizes.
The styled slider in the comic. |
See the slider in action in today's comic!
Amphibian.com comic for 29 January 2016 |
No comments:
Post a Comment