You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.6 KiB
JavaScript

2 months ago
function getRandomPosition(min, max) {
2 months ago
return Math.random() * (max - min) + min;
}
2 months ago
const bodyWidth = document.body.clientWidth;
const bodyHeight = document.body.clientHeight - document.querySelector('footer').clientHeight;
const headerHeight = document.querySelector('header').clientHeight;
let currentZIndex = 1; // Initialize a variable to keep track of the highest z-index
2 months ago
2 months ago
document.querySelectorAll('.draggable').forEach(draggable => {
draggable.style.left = `${getRandomPosition(0, bodyWidth)}px`;
draggable.style.top = `${getRandomPosition(headerHeight, bodyHeight)}px`;
2 months ago
2 months ago
draggable.addEventListener('mousedown', (event) => {
draggable.style.zIndex = ++currentZIndex; // Set the z-index to a higher value
2 months ago
2 months ago
const shiftX = event.clientX - draggable.getBoundingClientRect().left;
const shiftY = event.clientY - draggable.getBoundingClientRect().top;
2 months ago
function moveAt(pageX, pageY) {
2 months ago
draggable.style.left = `${pageX - shiftX}px`;
draggable.style.top = `${pageY - shiftY}px`;
2 months ago
}
function onMouseMove(event) {
moveAt(event.pageX, event.pageY);
}
document.addEventListener('mousemove', onMouseMove);
2 months ago
draggable.addEventListener('mouseup', () => {
2 months ago
document.removeEventListener('mousemove', onMouseMove);
2 months ago
}, { once: true });
2 months ago
2 months ago
draggable.addEventListener('dblclick', () => {
2 months ago
document.removeEventListener('mousemove', onMouseMove);
2 months ago
}, { once: true });
2 months ago
2 months ago
});
2 months ago
2 months ago
draggable.addEventListener('dragstart', () => false);
});