dragging thing
by Kingdaro
JavaScript
function createDraggable(style) {
style = (style==null) ? '' : style; // so that draggables can be defined w/o styles
style = style + ' -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none;'; // so that the cursor doesn't change
div = document.createElement('div'); // create the element
div.setAttribute('style', style); // apply style
div.style.position = 'absolute'; // make the draggable moveable
div.style.left = style.match('left') ? div.style.left : '0px'; // set the left and top if they don't exist
div.style.top = style.match('top') ? div.style.top : '0px';
div.style.cursor = 'move'; // set the cursor's style to the four arrow thing
div.addEventListener('mousedown', function(ev) {
self = ev.target; // convenience
self.dragging = 1; // set draggable on mouse down
self.dispx = ev.clientX - parseInt(self.style.left); // record displacement for accurate dragging
self.dispy = ev.clientY - parseInt(self.style.top);
self.style.opacity = 0.6; // make the element semitransparent
});
div.addEventListener('mouseup', function(ev) {
self = ev.target;
self.dragging = 0; // disable element dragging
self.style.opacity = 1; // make element fully opaque
});
div.addEventListener('mousemove', function(ev) {
self = ev.target;
if (self.dragging == 1) { // check if dragging is enabled
self.style.left = ev.clientX - self.dispx + 'px'; // go to mouse position with recorded displacement
self.style.top = ev.clientY - self.dispy + 'px';
}
});
return div; // to allow storing in a variable
}
div = createDraggable('font: 36pt arial bold; width: intrinsic; left: 200px; top: 200px;');
div.innerHTML = 'pls drag';
div.addEventListener('mousedown', function(ev){
self = ev.target;
...