I've made myself a JavaScript slider constructor. You can create new sliders and tell it what elements it should refer to.
var SliderControl = function (container, area, fill, action, actionWhenActive, actionWhenSet) {
'use strict';
var self = this;
this.action = action;
this.container = container;
this.area = area;
this.fill = fill;
this.element = container.find(area);
this.value = 0;
this.active = false;
this.actionWhenActive = actionWhenActive;
this.actionWhenSet = actionWhenSet;
$(document).on('mousemove', function (event) {
self.move(event, self);
});
$(document).on('mouseup', function (event) {
self.drop(event, self);
});
this.area.on('mousedown', function (event) {
self.grab(event, self);
});
};
SliderControl.prototype = {
action: this.action,
width: function () {
'use strict';
var calcWidth = ((this.value * 100) + '%');
this.fill.width(calcWidth);
},
update: function (event, self) {
'use strict';
if (this.actionWhenActive === true) {
this.action();
}
var direction, percent, container, area;
direction = event.pageX - this.element.offset().left;
percent = Math.min(Math.max(direction / this.element.width(), 0), 1.0);
this.value = percent;
this.width();
},
move: function (event, self) {
'use strict';
if (this.active === true) {
this.update(event);
}
},
grab: function (event, self) {
'use strict';
this.active = true;
self.update(event);
event.preventDefault();
},
drop: function (event, self) {
'use strict';
if (this.active === true) {
this.active = false;
this.action();
}
},
setValue: function (value) {
if (this.active === false) {
this.value = value;
this.width();
if (this.actionWhenSet === true) {
this.action();
}
}
}
};
If you want to try it out, go here.
I think there's a better way to set a custom function it should run when you drop the slider (or if actionWhenActive
is set to true, while you're dragging it) but I'm not sure what would be the most DRY way to do it.