jQuery UI widget: a slider displaying its value

August 6, 2013 at 11:47 AMMichele Mottini

For the billiard simulation user interface I wanted to select a value with a slider, displaying it at the same time – so I created a new jQuery UI custom widget based on the standard slider one. It is used to edit the coefficients of restitution and the rolling resistance coefficient here.  The Javascript source code is here, and the TypeScript definition file is here.

The widget is pretty basic: it supports only one value, the slider must be horizontal and the value is always displayed on the right of the slider.

Some problem I had writing the widget:

Case of the widget name

I originally called the widget ‘sliderWithValue’ using camel case. The name of the widget is used by default as the prefix for the complete name of the widget events – but converted to lowercase – so the name of the change event is ‘sliderwithvaluechange’ and NOT ‘sliderWithValuechange’. The documentation does not mention this conversion to lowercase.

I renamed the widget ‘valueslider’ to avoid this problem.

Setting the width of a ‘span’ element.

To space correctly the label containing the value I needed to convert a width from ems to pixels, to do this the only way I found is to create a dummy HTML element, setting its widths in ems and then getting its pixel width. The problem is that using Internet Explorer 10 this trick works fine using ‘span’ element, whereas in Chrome and Safari attempts to set the width of  this empty ‘span’ elements are ignored – it is necessary to use a ‘div’.

Events and widget ‘destroy’ method

The jQuery UI documentation instructs to wire events either directly in the widget options:

$( ".selector" ).slider({
  change: function( event, ui ) {}

or using the ‘on’ function:

$( ".selector" ).on( "slidechange", function( event, ui ) {} );

but they are not exactly equivalent: event handlers defined using ‘on’ are bot removed by the ‘destroy’ method of the widget, so if the code creates and destroys widgets dynamically it has to take care of removing the handlers defined using ‘on’.

Posted in: Programming

Tags: , , ,

Add comment

  Country flag

  • Comment
  • Preview