/** * Drag & drop & onrelease * -------------------------- */ function Slider(container) { this.container = container; this.thumb = container.getElementsByTagName("span")[0]; var self = this; this.dragThumb = DragController.add(this.thumb, function(value) { self.onRelease(value); }); this.parseValues(); } Slider.prototype = { parseValues:function() { var values = this.thumb.firstChild? this.thumb.firstChild.nodeValue : this.thumb.nodeValue; var tokens = /^([^(]+)\(([^,]+),([^)]+)\)/.exec(values); if(tokens) { this.input = document.getElementById(tokens[1]); this.minValue = parseInt(tokens[2], 10); this.maxValue = parseInt(tokens[3], 10); this.range = this.maxValue - this.minValue; EventListener.addEvent(this.input, 'change', this.updateSlider, this); } }, updateSlider:function(e) { var value = 100 * ((parseInt(this.input.value, 10) - this.minValue) / this.range); this.dragThumb.setValue(value); }, onRelease:function(value) { var inputValue = this.minValue + parseInt(this.range * value/100); this.input.value = inputValue; } } DragController = { elements:[], targets:[], add:function(node, handler) { var thumb = new DraggableThumb(this, node, handler); this.elements.push(thumb); return thumb; }, dragStart:function(e, element) { this.initX = e.clientX; this.initY = e.clientY; this.currentElement = element; this.moveEvent = EventListener.addEvent(document, 'mousemove', this.handleMouseMove, this); this.releaseEvent = EventListener.addEvent(document, 'mouseup', this.handleMouseUp, this); EventListener.cancelEvent(e); }, handleMouseMove:function(e) { var dx = e.clientX - this.initX; var dy = e.clientY - this.initY; this.currentElement.moveBy(dx, dy); this.initX += dx; this.initY += dy; EventListener.cancelEvent(e); }, handleMouseUp:function(e) { EventListener.removeEvent(this.moveEvent); EventListener.removeEvent(this.releaseEvent); this.currentElement.drop(e); this.currentElement = null; EventListener.cancelEvent(e); } } function DraggableThumb(controller, node, handler) { this.controller = controller; this.node = node; this.handler = handler; this.value = 0; this.clickEvent = EventListener.addEvent(node, 'mousedown', this.drag, this); } DraggableThumb.prototype = { drag:function(e) { this.controller.dragStart(e, this); }, drop:function(e) { try { this.handler(this.value); } catch (e) {} }, setValue:function(value) { if(value < 0) value = 0; if(value > 100) value = 100; var x = parseInt(value * (this.node.parentNode.offsetWidth - this.node.offsetWidth)/100, 10); this.node.style.left = x+'px'; }, moveBy:function(dx, dy) { var el = this.node; var tx = el.offsetLeft + dx; var ty = el.offsetTop + dy; var mx = parseInt(this.node.parentNode.offsetWidth - this.node.offsetWidth); var my = parseInt(this.node.parentNode.offsetHeight - this.node.offsetHeight); if(tx < 0) tx = 0; if(ty < 0) ty = 0; if(tx > mx) tx = mx; if(ty > my) ty = my; this.value = tx/mx * 100; el.style.left = tx + 'px'; el.style.top = ty + 'px'; } }