By CHI WAI LAU

Improved MooTools Slider

MooTools has a pretty slick slider. It’s flexible and easy to use, but I notice the user interaction isn’t perfect. When I click on the slider track, the knob will move to where I click. Now when I hold the click and try to drag the knob, it won’t follow where I move.

To support the click and drag interaction, we would want the slider to listen to both mousemove and mouseup events when users click on the track. Mousemove is for notifying the slider about the drag. Mouseup is for notifying the slider when to stop following the mouse. Here’s how I did it by extending the current slider:

var SliderEx = new Class({
  Extends: Slider,

  // Binds does not support inheritance..
  // Therefore, we have to declare the new bindings
  // as well as the existing ones.
  Binds: ['clickedElement', 'draggedKnob', 'scrolledElement',
      'releasedElement'],

  releasedElement: function(event) {
    document.removeEvent('mousemove', this.clickedElement);
    document.removeEvent('mouseup', this.releasedElement);
  },

  clickedElement: function(event) {
    if (event.target != this.knob) {
      document.addEvent('mousemove', this.clickedElement);
      event.stop();
    }
    document.addEvent('mouseup', this.releasedElement);

    this.parent(event);
  }
});

The second part of the code is only there for suppressing the text-selection cursor when dragging. I wish CSS could just take care of that instead. Oh well, I keep the code above and some demos in github. Feel free to follow it for improvements or bug fixes.

Demo / Slider

Demo / SliderEx