5

I am attempting to create a page where text appears in random locations. For this, I need the left and top distances in a DIV containing text to be created randomly. The following HTML is a basic idea of what I am thinking about.

<body>
    <script>
        function myFunction() {
            var leftvar = Math.round(Math.random()*1000);
            var topvar = Math.round(Math.random()*1000);
        }
        window.onload = myFunction;
    </script>
    <div style="left:leftvar; top:topvar;">
        <p>Test</p>
    </div>
</body>

How can I put variables in the style CSS of a DIV?

Also, any other ways to have a randomly relocating DIV would be appreciated.

1
  • You can't echo out values like that. You need to do it in the function. Once you have your random numbers, then you need to find the element document.getElementById for example, and change the .style properties. Commented Nov 29, 2013 at 16:22

2 Answers 2

8

Get the element with javascript and change it's style properties :

<head>
    <style>#myDiv {position: relative;}</style>
</head>
<body>
    <script>
        function myFunction() {
            var leftvar = Math.random()*1000;
            var topvar = Math.random()*1000;

            var elem = document.getElementById('myDiv');

            elem.style.left = leftvar + 'px';
            elem.style.top  = topvar + 'px';            
        }
        window.onload = myFunction;
    </script>
    <div id="myDiv">
        <p>Test</p>
    </div>
</body>
Sign up to request clarification or add additional context in comments.

3 Comments

This looks like it works and is exactly what I'm looking for, but it does not work. The text stays in place.
Add position:absolute to the div ;-) left/right/top/bottom need a position property to work.
@WilliamOffied - if that code is everything, setting left and top values won't do anything as the element has no position, see above comment!
0

You've got to try something like this:

<body>
    <script>
        function myFunction() {
            var leftvar = Math.random()*1000;
            var topvar = Math.random()*1000;
            var myDiv = document.getElementById('mydiv');
            myDiv.Left = leftvar;
            myDiv.Top = topvar;
        }
        window.onload = myFunction;
    </script>
    <div id='mydiv'>
        <p>Test</p>
    </div>
</body>

1 Comment

myDiv.Left = leftvar; myDiv.Top = topvar; - invalid. It should be myDiv.style.left

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.