resonancerumble/static/js/draggable.js
2024-08-09 17:00:28 +12:00

108 lines
3.4 KiB
JavaScript

function makeDraggable(element) {
let isDragging = false;
let startX, startY, initialLeft, initialTop;
// Check if the device is mobile
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (!isMobile) {
element.addEventListener("mousedown", dragStart, { passive: false });
document.addEventListener("mousemove", drag, { passive: false });
document.addEventListener("mouseup", dragEnd);
}
// For mobile devices, we'll only add touch events if we want to allow dragging
// If you want to completely disable dragging on mobile, you can remove these lines
element.addEventListener("touchstart", dragStart, { passive: true });
document.addEventListener("touchmove", drag, { passive: true });
document.addEventListener("touchend", dragEnd);
function dragStart(e) {
if (e.target.closest('.close-notification')) return;
if (isMobile) {
// On mobile, only start dragging if it's not a scrollable element
const isScrollable = e.target.closest('.widget-content') !== null;
if (isScrollable) return;
}
isDragging = true;
if (e.type === "touchstart") {
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
} else {
startX = e.clientX;
startY = e.clientY;
}
initialLeft = element.offsetLeft;
initialTop = element.offsetTop;
element.style.position = 'absolute';
element.style.zIndex = 1000;
}
function drag(e) {
if (!isDragging) return;
if (isMobile) {
// Prevent default only if we're actually dragging
e.preventDefault();
}
let clientX, clientY;
if (e.type === "touchmove") {
clientX = e.touches[0].clientX;
clientY = e.touches[0].clientY;
} else {
clientX = e.clientX;
clientY = e.clientY;
}
const deltaX = clientX - startX;
const deltaY = clientY - startY;
element.style.left = initialLeft + deltaX + 'px';
element.style.top = initialTop + deltaY + 'px';
}
function dragEnd(e) {
isDragging = false;
element.style.zIndex = '';
}
}
// Function to apply draggable functionality to an element
function applyDraggable(elementId) {
const element = document.getElementById(elementId);
if (element) {
element.classList.add('draggable');
makeDraggable(element);
}
}
// Apply draggable functionality to widgets and notification popups
function initDraggableElements() {
applyDraggable('uiWidget');
applyDraggable('infoWidget');
applyDraggable('classWidget');
applyDraggable('shopWidget');
// For notifications, we need to apply it dynamically when they're created
const originalShowNotification = notificationSystem.showNotification;
notificationSystem.showNotification = function(message) {
originalShowNotification.call(this, message);
const notifications = document.querySelectorAll('.custom-notification');
notifications.forEach(notification => {
notification.classList.add('draggable');
makeDraggable(notification);
});
};
}
// Call this function after your DOM is loaded
document.addEventListener('DOMContentLoaded', initDraggableElements);