William Offied
William Offied

Reputation: 57

Set Style Value as Javascript Variable

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.

Upvotes: 5

Views: 28826

Answers (2)

adeneo
adeneo

Reputation: 318342

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>

Upvotes: 8

kiks73
kiks73

Reputation: 3778

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>

Upvotes: 0

Related Questions