0

I need this one image to be in a random position on the screen every time i refresh the page, i found a javascript code that could work but i just don't know how to make it work.

this is my html

  <body>
    <p>
      find rufus
    </p>
    <img src="molerat.jpg" id="molerat"></img>
  </body>

javascript:

console.log();
function onloadFunction() {
  var amount = 10;
  var arrayIDs = "molerat"; 

  for (i=1;i<=amount;i++) {

   var element = document.getElementById(arrayIDs[i-1]);
   var positionInfo = element.getBoundingClientRect();
   var imgHeight = positionInfo.height;
   var imgWidth = positionInfo.width;


   var screenWidth = window.innerWidth;
   var screenHeight = window.innerHeight;

   var imgLeft = Math.floor(Math.random() * (screenWidth - imgWidth));
   var imgTop= Math.floor(Math.random() * (screenHeight - imgHeight));

   document.getElementById(arrayIDs[i-1]).style.top = imgTop+"px";
   document.getElementById(arrayIDs[i-1]).style.left = imgLeft+"px";
  }
}

css:

body{
  background-color:white;
  font-family: monospace;
  font-size: 50px;
}

img {
  position: absolute;
}
donnapls
  • 21
  • 5

2 Answers2

0

arrayIDs is not an array.

var arrayIDs = "molerat"; needs to be var arrayIDs = ["molerat"];

Also you only have 1 image so the amount needs to be set to 1

function onloadFunction() {
  var amount = 1;
  var arrayIDs = ["molerat"]; 

  for (i=1;i<=amount;i++) {

   var element = document.getElementById(arrayIDs[i-1]);
   var positionInfo = element.getBoundingClientRect();
   var imgHeight = positionInfo.height;
   var imgWidth = positionInfo.width;


   var screenWidth = window.innerWidth;
   var screenHeight = window.innerHeight;

   var imgLeft = Math.floor(Math.random() * (screenWidth - imgWidth));
   var imgTop= Math.floor(Math.random() * (screenHeight - imgHeight));

   document.getElementById(arrayIDs[i-1]).style.top = imgTop+"px";
   document.getElementById(arrayIDs[i-1]).style.left = imgLeft+"px";
  }
}

onloadFunction();
body{
  background-color: white;
  font-family: monospace;
  font-size: 50px;
}

img {
  position: absolute;
}
<p>
  find rufus
</p>
<img src="https://picsum.photos/200" id="molerat" />
Reyno
  • 6,119
  • 18
  • 27
  • thank you! if i run this snippet it works but i get the error: cannot read property 'getboundingclientrect' of null. why is that? – donnapls Sep 16 '20 at 09:30
  • @donnapls Did you change the amount down from 10 to 1? It just means it cant find the element you specified. So either the ID doesn't exist or your amount is to high. Amount needs the be the amount of ID's you have – Reyno Sep 16 '20 at 10:27
0

Your onloadFunction needs to be invoked, when the page loads. If you're using jQuery in your project, then $(document).ready(...) is the way to go:

$(onloadFunction)

Otherwise you might want to check this question for pure JavaScript $(document).ready(...) alternatives.

eugenesqr
  • 589
  • 6
  • 19