How can you change the coordinates of an image in javascript?

Viewed 1982

Hey I want to change the image position(x,y) or (top/left) I'm not sure whats the different.. I am able to get the currect coordinates of the image however I can't change it..

I tried doing:

var ball = document.getElementById("ball");

ball.x = 50;

But it didn't change it.

Here's the full code:

<html onmousemove="showCoords(event)">
<head>
</head>
<body>
    <img id='ball' src="ball.png" alt="Logo"style="margin-left: 50%;
    margin-right: auto; margin-top: 25%;width:70px;height:70px;">
    <p id="demo"></p>
    <script>
        function showCoords(event) 
        {
            var x = event.clientX;
            var y = event.clientY;
            var ball = document.getElementById("ball");
            var ballX = ball.getBoundingClientRect().x;
            var ballY = ball.getBoundingClientRect().y;
            var mouse = "mouse: X coords: " + x + ", Y coords: " + y + ' Ball: X coords: ' + ballX + ', Y coords: ' + ballY;
            document.getElementById("demo").innerHTML = mouse;
            if(x < 100) // it does enter this statement
            {
                ball.getBoundingClientRect().x += 500; // not doing anything
            }

        }
    </script>
</body>

I thought maybe its something with the position of the image however I cant get it to work..

1 Answers

I think you are looking for something like this:

function move(){
    let ball = document.getElementById('ball')
    let ballX = ball.getBoundingClientRect().x
    ball.style.position = 'absolute'
    ball.style.top =  ballX + 500
 }
Related