function drags(dragElement, resizeElement, container) {
dragElement.addEventListener('mousedown', startDrag);
dragElement.addEventListener('touchstart', startDrag);
function startDrag(e) {
e.preventDefault();
dragElement.classList.add('ba-draggable');
resizeElement.classList.add('ba-resizable');
let startX = e.pageX || e.touches[0].pageX;
let dragWidth = dragElement.offsetWidth;
let posX = dragElement.getBoundingClientRect().left + dragWidth - startX;
let containerOffset = container.getBoundingClientRect().left;
let containerWidth = container.offsetWidth;
let minLeft = containerOffset + 10;
let maxLeft = containerOffset + containerWidth - dragWidth - 10;
function onMove(e) {
let moveX = e.pageX || e.touches[0].pageX;
let leftValue = moveX + posX - dragWidth;
if (leftValue < minLeft) {
leftValue = minLeft;
} else if (leftValue > maxLeft) {
leftValue = maxLeft;
}
let widthValue = ((leftValue + dragWidth / 2 - containerOffset) / containerWidth) * 100 + '%';
document.querySelector('.ba-draggable').style.left = widthValue;
document.querySelector('.ba-resizable').style.width = widthValue;
}
function stopDrag() {
dragElement.classList.remove('ba-draggable');
resizeElement.classList.remove('ba-resizable');
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', stopDrag);
document.removeEventListener('touchmove', onMove);
document.removeEventListener('touchend', stopDrag);
}
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', stopDrag);
document.addEventListener('touchmove', onMove);
document.addEventListener('touchend', stopDrag);
}
}
function beforeAfter(cur) {
if (!cur) return;
const resizeImg = cur.querySelector('.resize img');
resizeImg.style.width = cur.offsetWidth + 'px';
drags(cur.querySelector('.handle'), cur.querySelector('.resize'), cur);
window.addEventListener('resize', () => {
resizeImg.style.width = cur.offsetWidth + 'px';
});
}