skip to Main Content

I created a button that must move to a random position when it is clicked.
I created a html page with a button that has a
function.
The function is called and I created two variables height and width to generate a random height and width . But the document.style.top property is not working as expected . Please help me with a proper solution.
Thanks

The html code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Move Button</title>
</head>
<body>
    
    <script src="Script.js" type="text/Javascript"> </script>
    <button id="my-button" onclick= "MoveText()" >Click me</button>


    <style>
        body {
             background-color: rgb(62, 59, 229);
             color:yellow;
             font-weight: 500;
             letter-spacing: 2;
             font-size: 35px;
             
         }
     </style>
 
    
    
</body>
</html>

Javascript file (Script.js) :

function MoveText() {    
    const Button_select=document.getElementById('my-button')
    console.log(Button_select)

    var height=String(Math.floor(Math.random()*500))+'px'
    var width=String(Math.floor(Math.random()*900))+'px'

    Button_select.style.top = height;
    Button_select.style.left = width;


    Button_select.style.color = 'Red'
}




I also tried inline Javascript but didn’t work.
I also added position property in the style section and tried setting it to absolute and relative but it didn’t work.
I expect the button to appear in a random position when clicked.

2

Answers


  1. Set the CSS position of the button to a value other than static (default).

    Button_select.style.position = 'fixed';
    
    Login or Signup to reply.
  2. That is because your button is not positioned correctly. You need to position it fixed or absolute (relative to some parent element) for top/bottom/left/right css properties to work.

    Change your HTML button code to

    <button id="my-button" style="position: fixed;" onclick= "MoveText()" >Click me</button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search