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!

42 thoughts on “How to make a button that teleports randomly on the website onclick”

  1. Without going into it too much:

    document.getElementById('button').onclick = function(){ = Math.floor(Math.random()*100)+'%';
    <button id='button'>Teleport</button>
  2. document.addEventListener("DOMContentLoaded", function(){
      var rnd = Math.random()
      var button = document.getElementById('magic');
      if (rnd > .25) {
        = 'block' = Math.random() * 100 + '%' = Math.random() * 100 + '%'
    body {
      position: relative;
      height: 100vh;
    button {
      position: absolute;
      top: 0;
      left: 0;
      display: none;
    <button id='magic' onclick='myFunction()'>teleport</button>

Leave a Comment