teaching machines

Making a jQuery slider do something

June 1, 2012 by . Filed under keystrokes, public.

Getting a slider to display was the first step. The end goal is to make the slider scrub through a series of snapshots of a text file. In between, let’s just figure out how to map the tick to a timestep.

jQuery sliders are discrete; they can only be scrubbed to integral positions. Since the text movies they are scrubbing through may be 100, 103.5, 15.7, etc., second longs, I must range map the slider’s tick position (in [0, n], where n is the maximum number of ticks) to the appropriate timestep (in [0, nseconds], where nseconds is the number of seconds in the movie). I do that by finding the proportion of the current tick position to the maximal tick position, and applying that proportion to the number of seconds.

I make the maximal number of ticks a large number to provide a good number of reachable timesteps. If n was only 10, for example, the slider would only let the user access 10 different timesteps. For a 3 hour text movie, that’s not very helpful.

Here’s the script I ended up with:

var maxTicks = 1000000; jQuery(function() { jQuery("#slider").slider({ value: 0, min: 0, max: maxTicks, step: 1, slide: function(event, ui) { var nTicks = ui.value; var nSeconds = jQuery('#nseconds').val(); jQuery('#tick').val(nTicks); jQuery('#time').val(nTicks / maxTicks * nSeconds); } }); jQuery("#slider").css('margin', '10px'); }); // Add a div which will hold the slider. document.write('<div id="slider"></div>'); // Create box for max intensity, which slider proportional // will range map to. document.write('<p>'); document.write('<label for="nseconds"># of seconds:</label>'); document.write('<input type="text" id="nseconds" value="33" />'); document.write('</p>'); // Create box for slider tick number. document.write('<p>'); document.write('<label for="tick">tick:</label>'); document.write('<input type="text" id="tick" />'); document.write('</p>'); // Create box for slider value. document.write('<p>'); document.write('<label for="time">time:</label>'); document.write('<input type="text" id="time" />'); document.write('</p>');

When embedded in the page, the script produces: