javascript – Draggable image working fine on Windows/macOS but not working at all on iOS/Android


In my HTML I have the following code:

<div class="anagram" id="draggable-container">
    <img width="50px" class="draggable" src="images/A.png" alt="Letter A on a Scrabble tile." style="rotate: 20deg;">
</div>

There are several images but I’ll just show one to keep the code simple.

To make the image draggable I’m using the following js file:

// Drag and drop functionality
const draggableElements = document.querySelectorAll('.draggable');
const container = document.getElementById('draggable-container');

draggableElements.forEach((draggableElement) => {
    let offsetX, offsetY, isDragging = false;

    draggableElement.addEventListener('mousedown', (event) => {
        event.preventDefault(); // Prevent default drag-and-drop behavior

        isDragging = true;

        offsetX = event.clientX - draggableElement.getBoundingClientRect().left;
        offsetY = event.clientY - draggableElement.getBoundingClientRect().top;

        document.addEventListener('mousemove', handleDrag);
        document.addEventListener('mouseup', () => {
            isDragging = false;
            document.removeEventListener('mousemove', handleDrag);
        });
    });

    function handleDrag(event) {
        if (!isDragging) return;

        const x = event.clientX - offsetX - container.getBoundingClientRect().left;
        const y = event.clientY - offsetY - container.getBoundingClientRect().top;

        const maxX = container.clientWidth - draggableElement.clientWidth;
        const maxY = container.clientHeight - draggableElement.clientHeight;

        // Ensure the image stays within the container
        const constrainedX = Math.min(Math.max(0, x), maxX);
        const constrainedY = Math.min(Math.max(0, y), maxY);

        draggableElement.style.left = `${constrainedX}px`;
        draggableElement.style.top = `${constrainedY}px`;
    }
});

This works perfectly on laptops and desktops in both Windows and macOS for any browser.

However it doesn’t work at all on mobile devices (phones/tablets) either iOS or Android!

Can anyone see what’s wrong?

On mobile devices nothing happens at all. On laptops all is OK including touch screens.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img