javascripthtmlfor-looponclick

I want to change position randomly


The onclick event does not repeat

I want the target to move randomly every time I click on it but it only moves once.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <img src="target.png" id="tg" onclick="target()">

  <script>
  var a = document.getElementById("tg");
  var x = Math.random()*window.innerWidth;
  var y = Math.random()*window.innerHeight;

  function target(){a.style.left = x + "px", a.style.top = y + "px";}
    
  for (var i = 0; i < 5; i++) {function target(){a.style.left = x + "px", a.style.top = y + "px";}}
    
  </script>
</body>

</html>

Solution

  • If you want the target to move randomly, you need to use a random number and you need to set it inside the function so the values would update every time you click and the target() function is called.

    Also, make sure you are using 'position: absolute;'.

    Here is an example on how it can be done:

    <body>
        <img src="target.png" id="tg" onclick="target()"   style="position: absolute;">
    
        <script>
            var a = document.getElementById("tg");
    
            function target() {
                var x = Math.random() * (window.innerWidth - a.clientWidth);
                var y = Math.random() * (window.innerHeight - a.clientHeight);
                a.style.left = x + "px";
                a.style.top = y + "px";
            }
        </script>
    </body>