xssbook2/web/public/js/shared/modal.js
2024-03-30 12:14:42 -04:00

64 lines
1.4 KiB
JavaScript

$(document).on('click', ".modal-close", (o) => {
$(o.target).closest('.modal-container').remove();
});
const initDrag = (header, modal, container) => {
let drag = false;
let mouseX, mouseY, modalX, modalY;
const onStart = (e) => {
e = e || window.event;
e.preventDefault();
mouseX = e.clientX;
mouseY = e.clientY;
drag = true;
};
const onDrag = (e) => {
e = e || window.event;
e.preventDefault();
if (!drag) {
return;
}
modalX = mouseX - e.clientX;
modalY = mouseY - e.clientY;
mouseX = e.clientX;
mouseY = e.clientY;
let posX = (modal.offsetLeft - modalX),
posY = (modal.offsetTop - modalY);
let minX = modal.offsetWidth / 2,
minY = modal.offsetHeight / 2;
let maxX = container.offsetWidth - minX,
maxY = container.offsetHeight - minY;
posX = Math.max(minX, Math.min(maxX, posX));
posY = Math.max(minY, Math.min(maxY, posY));
posX = posX / container.offsetWidth * 100;
posY = posY / container.offsetHeight * 100;
modal.style.left = posX + "%";
modal.style.top = posY + "%";
};
const onEnd = () => {
drag = false;
};
header.onmousedown = onStart;
container.onmousemove = onDrag;
container.onmouseup = onEnd;
};
observe('body', '.modal-header', function(el) {
let header = $(el);
let modal = header.closest('.modal');
let container = header.closest('.modal-container');
initDrag(
header[0], modal[0], container[0]
);
});