Skip to content

Instantly share code, notes, and snippets.

@keevitaja
Last active July 20, 2016 20:05
Show Gist options
  • Save keevitaja/5734bbdcef7f65db3df3edd85f2849e0 to your computer and use it in GitHub Desktop.
Save keevitaja/5734bbdcef7f65db3df3edd85f2849e0 to your computer and use it in GitHub Desktop.
javascript draggable & resizable elements example
'use strict';
class Transformable {
constructor(element) {
this.element = element;
this.dragging = false;
this.resizing = false;
}
offsetX(event) {
return event.pageX - this.element.offsetLeft;
}
offsetY(event) {
return event.pageY - this.element.offsetTop;
}
isDraggable(event) {
return this.offsetY(event) <= 10 && event.ctrlKey;
}
isResizable(event) {
let x = this.element.offsetWidth - this.offsetX(event) <= 10;
let y = this.element.offsetHeight - this.offsetY(event) <= 10;
return x && y && event.ctrlKey;
}
isMutating() {
return this.dragging || this.resizing;
}
cursor(event) {
if (this.isDraggable(event) || this.dragging) return 'move';
if (this.isResizable(event) || this.resizing) return 'se-resize';
return 'default';
}
positions(event) {
return {x: event.pageX, y: event.pageY};
}
drag(event) {
this.element.style.left = this.element.offsetLeft + event.pageX - this.dragging.x + 'px';
this.element.style.top = this.element.offsetTop + event.pageY - this.dragging.y + 'px';
this.dragging = this.positions(event);
}
resize(event) {
this.element.style.width = this.element.offsetWidth + event.pageX - this.resizing.x + 'px';
this.element.style.height = this.element.offsetHeight + event.pageY - this.resizing.y + 'px';
this.resizing = this.positions(event);
}
listen() {
this.element.addEventListener('mousemove', (event)=> {
this.element.style.cursor = this.cursor(event);
});
this.element.addEventListener('mousedown', (event)=> {
if (this.isDraggable(event)) this.dragging = this.positions(event);
if (this.isResizable(event)) this.resizing = this.positions(event);
if (this.isMutating()) document.querySelector('body').style['-webkit-user-select'] = 'none';
});
document.addEventListener('mouseup', (event)=> {
if ( ! this.isMutating()) return false;
this.dragging = false;
this.resizing = false;
document.querySelector('body').style['-webkit-user-select'] = 'auto';
});
document.addEventListener('mousemove', (event)=> {
if (this.dragging) this.drag(event);
if (this.resizing) this.resize(event);
});
return this;
}
}
const main = (new Transformable(document.getElementById('main'))).listen();
const comm = (new Transformable(document.getElementById('comm'))).listen();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment