Dmitry Pekach
Dmitry Pekach

Reputation: 161

appendChild removes style

I tried to use appendChild function in order to create a new image node with some style properties. After using it, all properties vanishes. The images supposed to be randomly positioned on the leftSide div, however, actually, they are put align in a row.

<html>
  <head>
    <title>Matching Game</title>
    <style>
        #rightSide {
            position: absolute;
            left: 700px;
            border-left: 1px solid black;
            width:700px; 
            height:700px;
        }

        #leftSide {
            width:700px; 
            height:700px;
            position: absolute;

        }

    </style>
</head>



<body onload="generateFaces()">
    <h1>Matching Game</h1>
    <p>Click on the extra smiling face on the left</p>

    <div id='leftSide'>

    </div>

    <div id='rightSide'>

    </div>

    <script>
        var numberOfFaces = 5;
        var theLeftSide = document.getElementById('leftSide');


        var generateFaces = function() {
            for(var i = 0; i < numberOfFaces; i++)
                {
                  var img = document.createElement('img');
                    img.src = 'smile.png';
                    img.style.top =  Math.floor(Math.random()*600);
                    img.style.left = Math.floor(Math.random()*600);
                    theLeftSide.appendChild(img);
                }
        }
    </script>
</body>


</html>

https://i.sstatic.net/fZaYA.png

Upvotes: 0

Views: 78

Answers (2)

KMathmann
KMathmann

Reputation: 444

that should solve your problem.

var img = document.createElement('img');
img.style.top =  Math.floor(Math.random()*600) + 'px';

Upvotes: 1

Quentin
Quentin

Reputation: 943510

Math.floor(Math.random()*600); is going to return a number. Unless the value is 0, the CSS left and top properties require a length. Lengths have units.

Additionally, you haven't changed the position property away from static, so the left and top properties will have no effect as they apply only to positioned elements.

Upvotes: 2

Related Questions