How can I move an image using X and Y cordinates of a click
I am trying to add a function to my site that when a user clicks in a random location an image appears in said location.
This is my current code all within my HTML
, Im guessing I have to use xpos
and ypos
as their outputs in some sort of position tag?
<script> function showCoords(event) { var x = event.clientX; var y = event.clientY; var coords = "X coords: " + x + ", Y coords: " + y; document.getElementById("demo").innerHTML = coords; document.getElementById("xpos").innerHTML = x; document.getElementById("ypos").innerHTML = y; } </script>
<!DOCTYPE html> <html onclick="showCoords(event)" > <link rel="stylesheet" href="/style.css"> <body> <h2 >Click this heading to get the x (horizontal) and y (vertical) coordinates of the mouse pointer when it was clicked.</h2> <p><strong>Tip:</strong> Try to click different places in the heading.</p> <img src="https://uploads-ssl.webflow.com/5eed5cc775d5b7fa27c3d7f5/5eef73e7ad8dd5e992850fea_Video-Thumbnail.png" alt="Girl in a jacket" > <p id="demo"></p> <p id="xpos"></p> <p id="ypos"></p> on </body> </html>
You can do this by using JS and applying styling and making the image position
to absolute
to that image according to clicked cords x
and y
Click anywhere on the snippet screen to see the img
appear / move there.
Run snippet below.
function showCoords(event) { var x = event.clientX; var y = event.clientY; var coords = "X coords: " + x + ", Y coords: " + y; document.getElementById("demo").innerHTML = coords; document.getElementById("xpos").innerHTML = x; document.getElementById("ypos").innerHTML = y; var image = document.getElementById("myImage"); image.style.display = ''; image.style.position = 'absolute'; image.style.left = x + 'px'; image.style.top = y + 'px'; }
<!DOCTYPE html> <html onclick="showCoords(event)"> <link rel="stylesheet" href="/style.css"> <body> <h2>Click this heading to get the x (horizontal) and y (vertical) coordinates of the mouse pointer when it was clicked.</h2> <p><strong>Tip:</strong> Try to click different places in the heading.</p> <img id="myImage" src="https://uploads-ssl.webflow.com/5eed5cc775d5b7fa27c3d7f5/5eef73e7ad8dd5e992850fea_Video-Thumbnail.png" alt="Girl in a jacket"> <p id="demo"></p> <p id="xpos"></p> <p id="ypos"></p> </body> </html>