Hello! I am trying to have one of my questions a freeform drag and drop (e.g., participants will move icons on a screen) and I want to save either the final image or the coordinates of the icons. I only want 2 of the items to move (imagine there is a square, and the icon for ‘lunch’ doesn’t move, and you move an icon for ‘breakfast’ and an icon for ‘dinner’. I tried the following code but I cannot seem to make it work. I was hoping that someone could have better insight as to what needs to be corrected. Thank you in advance!
<div style="position: relative; width: 600px; height: 400px; margin: 20px auto;
background: url('https://uwartsandsciences.pdx1.qualtrics.com/ControlPanel/Graphic.php?IM=IM_eXemGs5D7yFpvhz')
no-repeat center; background-size: contain; border: 1px solid #ccc;"
id="slide-container">
<img style="width: 50px; position: absolute; top: 150px; left: 450px; cursor: grab;"
src="https://uwartsandsciences.pdx1.qualtrics.com/ControlPanel/Graphic.php?IM=IM_vrPsqekWIt26Rxt"
id="breakfast" alt="Breakfast">
<img style="width: 50px; position: absolute; top: 180px; left: 230px; cursor: default;"
src="https://uwartsandsciences.pdx1.qualtrics.com/ControlPanel/Graphic.php?IM=IM_F7HsYTB4JUTYy8v"
id="lunch" alt="Lunch">
<img style="width: 50px; position: absolute; top: 250px; left: 450px; cursor: grab;"
src="https://uwartsandsciences.pdx1.qualtrics.com/ControlPanel/Graphic.php?IM=IM_aWecqmidZuBBznx"
id="dinner" alt="Dinner">
</div>
<script>
// Get references to the breakfast and dinner images (only these will be draggable)
const draggableIcons = document.querySelectorAll('#breakfast, #dinner');
draggableIcons.forEach(icon => {
let isDragging = false;
let offsetX, offsetY;
// Start dragging when mouse is pressed on the icon
icon.addEventListener("mousedown", (event) => {
isDragging = true;
offsetX = event.clientX - icon.getBoundingClientRect().left;
offsetY = event.clientY - icon.getBoundingClientRect().top;
icon.style.cursor = "grabbing"; // Change cursor to 'grabbing'
event.preventDefault(); // Prevent other default behaviors (like image drag)
// Add mousemove and mouseup event listeners to manage drag
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
});
// Handle moving the icon
function onMouseMove(event) {
if (isDragging) {
icon.style.left = `${event.clientX - offsetX}px`;
icon.style.top = `${event.clientY - offsetY}px`;
}
}
// Stop dragging when mouse is released
function onMouseUp() {
isDragging = false;
icon.style.cursor = "grab"; // Reset cursor to 'grab'
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
}
});
</script>