Search code examples
javascripthtmlposition

How to update position of div with javascript


This is my first time posting here so I hope I'm doing it right. I appreciate any help I can get.

I am trying to update the position of a div using a Javascript function that, when called by the click of a button, calculates random numbers and then uses these numbers to change the position of the div. Unfortunately, clicking the button does not change the position of the div.

This is my HTML:

<body>

<p>Want to see something cool?</p>
<button id = "funbutton" onclick="SeeWhatHappens()">Click here!</button>

<div id = "newdiv" class="a"></div>

</body>

And this is my Javascript function:

function SeeWhatHappens() {
var numRand = Math.floor(Math.random() * 501);
var divsize = 50;
var posx = (Math.random() * document.width() - divsize).toFixed();
var posy = (Math.random() * document.height() - divsize).toFixed();
var div = document.getElementById('newdiv');
div.style.left = posx;
div.style.top = posy;
}

Here is my full code: http://jsfiddle.net/6hnLx6qc/

What am I doing wrong?


Solution

  • You have two problems. The first one is that there is no such methods width and height on document object. You can use window.innerWidth/innerHeight instead. And the second one, you need to use px units for style.left/top values:

    function SeeWhatHappens() {
        var numRand = Math.floor(Math.random() * 501);
        var divsize = 50;
        var posx = (Math.random() * window.innerWidth - divsize).toFixed();
        var posy = (Math.random() * window.innerHeight - divsize).toFixed();
        var div = document.getElementById('newdiv');
        div.style.left = posx + 'px';
        div.style.top = posy + 'px';
    }
    

    Demo: http://jsfiddle.net/6hnLx6qc/7/