'How to make a button that teleports randomly on the website onclick

At the moment I wanted to create a button that teleports randomly back and forth on my website. As I am very new to JavaScript, I did not get it right. That's why I don't have a code. I found this question but it didn't help me.

Here's the Code i used:

document.getElementById("button").style.margin = Math.floor(Math.random() * 100);
<button id="button">Teleport</button>

Do you have any ideas how I could do this with HTML, CSS and JavaScript?

Thanks in advance!



Solution 1:[1]

Without going into it too much:

addEventListener('load', ()=>{ // load
const but = document.getElementById('button'), bS = but.style, bod = document.body;
but.onclick = function(){
  let m = bod.getBoundingClientRect(), mw = m.width, mh = m.height, b = this.getBoundingClientRect(), x = Math.floor(Math.random()*mw);
  let y = Math.floor(Math.random()*mh), w = b.width, h = b.height, xw = mw-w, yh = mh-h;
  bS.top = (y > yh ? yh : y)+'px';
  bS.left = (x > xw ? xw : x)+'px';
}
});// end load
*{
  box-sizing:border-box;
}
html,body{
  width:100%; height:100%; margin:0; padding:0;
}
body{
  position:relative;
}
body>*{
  position:absolute;
}
#button{
  margin:0;
}
<button id='button'>Teleport</button>

Solution 2:[2]

document.addEventListener("DOMContentLoaded", function(){

  var rnd = Math.random()
  var button = document.getElementById('magic');
      
  if (rnd > .25) {

    
    button.style.display = 'block'
    button.style.top = Math.random() * 100 + '%'
    button.style.left = Math.random() * 100 + '%'
  }else{
    button.style.display='none'
  }
 
});
  
body {
  position: relative;
  height: 100vh;
}

button {
  position: absolute;
  top: 0;
  left: 0;
  display: none;
}
<button id='magic' onclick='myFunction()'>teleport</button>

Solution 3:[3]

Use Math.random() * 101 to randomly generate a number of 0 - 100. I generate 2 numbers for the y and the x axis. That way I change the position for top and left according to randomly generated number

function jump() {
  var x = Math.round((Math.random() * 101)) + "%",
      y = Math.round((Math.random() * 101)) + "%";
  document.getElementById("jump").style.left = x;
  document.getElementById("jump").style.top = y;
}
body {
  margin: 0;
}

.button-container {
  position: relative;
  width: calc(100vw - 100px);
  height: calc(100vh - 20px);
}

button {
  position: absolute;
  width: 100px;
  height: 20px;
}
<div class="button-container">
  <button id="jump" onclick="jump()">Click Me</button>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 tacoshy