javascripthtmlrandomstyles

JavaScript - Math.floor(Math.random()) - Reposition <img> element


I am trying to develop a function that randomly repositions an element on a web document. My current JavaScript program does not randomly change the element.style.left and element.style.top values of the element id = "image". Thanks for your help!

<html> <body>

<img id="image" src="happy.jpg" style="position:absolute;left:0px; 
top:0px; width:50px; height:50px;" />

<button onclick="RandomPositions()"> Random Position </button>

<script>
 function RandomPositions() {
    var Hero = document.getElementById("image");
    var x = Math.floor(Math.random() * 300);
    var HeroX = Hero.style.left;
    HeroX = x + 'px';
    var y = Math.floor(Math.random() * 300);
    var HeroY = Hero.style.top; 
    HeroY = y + 'px';
 }
</script>
</body>
</html>

Solution

  • I suggest to use only the element itself, because you had as reference a primitive value (string), not the reference to style.

     function RandomPositions() {
        var Hero = document.getElementById("image");
        var x = Math.floor(Math.random() * 300);
        var y = Math.floor(Math.random() * 300);
        Hero.style.top = y + 'px';
        Hero.style.left = x + 'px';       
     }
    <img id="image" src="http://lorempixel.com/75/75/" style="position:absolute;left:0px; 
    top:0px; width:50px; height:50px;" />
    <button onclick="RandomPositions()"> Random Position </button>