-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresibar.lib.js
More file actions
78 lines (58 loc) · 2.71 KB
/
resibar.lib.js
File metadata and controls
78 lines (58 loc) · 2.71 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
(function() {
"use strict";
/**
* Enables resizable behavior on a specified element by dragging a resizer handle.
*
* @param {HTMLElement} resizer resizer Element used to drag and resize the bar
* @param {HTMLElement} bar The bar element to resize (e.g., sidebar-(left|right|top|bottom))
* @param {String} dir The direction of resizing (e.g., xl, xr, yt, yb)
*/
function resibar(resizer, bar, dir) {
let initPos, initVal, axis = dir.slice(0, 1).toUpperCase(),
// Store the original cursor style
initCursor = document.body.style.cursor,
// Decide property to change: width for 'X', height for 'Y'
prop = {X: "Width", Y: "Height"}[axis],
// Check if resizing is from right or bottom (affects calculation direction)
isRT = /^(?:r|b)$/i.test(dir.slice(1));
// Function to stop the resize interaction
function stopResize() {
document.body.style.cursor = initCursor; // Restore the original cursor
// Remove event listeners to stop resizing
document.removeEventListener("mousemove", resize);
document.removeEventListener("touchmove", resize);
document.removeEventListener("touchend", stopResize);
document.removeEventListener("mouseup", stopResize);
}
// Function to handle resizing while mouse/touch is moving
function resize(e) {
e = e.touches && e.touches[0] || e; // Normalize mouse and touch event
// Difference from initial position
let axisVal = e["client" + axis] - initPos;
// Calculate new value for width/height
let value = (initVal + (isRT ? -axisVal : axisVal));
// Apply the new size to the element
bar.style[prop.toLowerCase()] = value + "px";
}
// Function to start resizing interaction
function startResize(e) {
e.stopPropagation(); // Prevent event bubbling
e.preventDefault(); // Prevent default browser behavior
// Set cursor to appropriate resize style
let cursor = {X: "ew", Y: "ns"}[axis] + "-resize";
document.body.style.cursor = cursor;
e = e.touches && e.touches[0] || e; // Normalize mouse and touch event
initVal = bar["client" + prop]; // Get initial width or height
initPos = e["client" + axis]; // Get initial mouse/touch position
// Add listeners to track movement and end of interaction
document.addEventListener("mousemove", resize);
document.addEventListener("touchmove", resize);
document.addEventListener("mouseup", stopResize);
document.addEventListener("touchend", stopResize);
}
// Attach event listeners to the resizer element
resizer.addEventListener("mousedown", startResize);
resizer.addEventListener("touchstart", startResize, {passive: false});
}
window.resibar = resibar;
})();