Skip to main content

Handige JS Functions

Prevent dragging on page

let initialX, initialY;
let dragging = false;

document.addEventListener('mousedown', function (event) {
    // Store the initial mouse position when the mouse button is pressed
    initialX = event.clientX;
    initialY = event.clientY;
    dragging = true; // Set dragging to true on mousedown
});

document.addEventListener('mouseup', function () {
    dragging = false; // Reset dragging on mouseup
});

document.addEventListener('mousemove', function (event) {
    if (dragging) {
        // Calculate the distance moved
        let deltaX = Math.abs(event.clientX - initialX);
        let deltaY = Math.abs(event.clientY - initialY);
        let distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); // Pythagoras theorem to calculate the distance

        // If the distance dragged is more than 100 pixels, blank the screen
        if (distance > 400) {
            document.body.style.visibility = 'hidden'; // Blank the page
            setTimeout(function () {
                document.body.style.visibility = 'visible'; // Restore
            }, 200); 

            // Reset dragging to prevent repeated triggering
            dragging = false;
        }
    }
});