-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresize.js
More file actions
60 lines (58 loc) · 2.06 KB
/
resize.js
File metadata and controls
60 lines (58 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/* https://medium.com/the-z/making-a-resizable-div-in-js-is-not-easy-as-you-think-bda19a1bc53d */
window.makeResizableDiv = function ( element ) {
const resizers = element.querySelectorAll( '.resizer' ),
minWidth = 450,
minHeight = 300;
let originalWidth = 0,
originalHeight = 0,
originalX = 0,
originalY = 0,
originalMouseX = 0,
originalMouseY = 0,
currentResizer;
function resize( e ) {
const sides = currentResizer.dataset.side.split( ' ' );
if ( sides.includes( 'b' ) ) { /* Bottom */
const height = originalHeight + ( e.pageY - originalMouseY );
if ( height > minHeight ) {
element.style.height = `${ height }px`;
}
} else if ( sides.includes( 't' ) ) { /* Top */
const height = originalHeight - ( e.pageY - originalMouseY );
if ( height > minHeight ) {
element.style.height = `${ height }px`;
element.style.top = originalY + ( e.pageY - originalMouseY ) + 'px';
}
}
if ( sides.includes( 'r' ) ) { /* Right */
const width = originalWidth + ( e.pageX - originalMouseX );
if ( width > minWidth ) {
element.style.width = `${ width }px`;
}
} else if ( sides.includes( 'l' ) ) { /* Left */
const width = originalWidth - ( e.pageX - originalMouseX );
if ( width > minWidth ) {
element.style.width = `${ width }px`;
element.style.left = originalX + ( e.pageX - originalMouseX ) + 'px';
}
}
}
resizers.forEach( ( resizer ) => {
resizer.addEventListener( 'mousedown', ( e ) => {
e.preventDefault();
const compStyle = getComputedStyle( element, null ),
rect = element.getBoundingClientRect();
originalWidth = parseFloat( compStyle.getPropertyValue( 'width' ).replace( 'px', '' ) );
originalHeight = parseFloat( compStyle.getPropertyValue( 'height' ).replace( 'px', '' ) );
originalX = rect.left;
originalY = rect.top;
originalMouseX = e.pageX;
originalMouseY = e.pageY;
currentResizer = e.target;
window.addEventListener( 'mousemove', resize, false );
window.addEventListener( 'mouseup', () => {
window.removeEventListener( 'mousemove', resize );
}, false );
} );
} );
};