Pankaj Andhale
Pankaj Andhale

Reputation: 403

javascript image position

I'm trying to put smile images at random positions on the left side div.But the images are not appearing in random order , rather it is showing images serially. Why is this happening?

<html>
    <head>
    <h1>Matching Game</h1>
    <p>Click on the extra smiling face on the left</p>
    <div id= "leftSide"></div>
    <div id = "rightSide"></div>
    <style>
        img1 {position:absolute}
        div {position:absolute; width:500px;height: 500px}
        #rightSide {left:500px;border-left: 1px solid black}
    </style>
         <script>
            var numberOfFaces =5,i;
            var theLeftSide = document.getElementById("leftSide");


            function generateFaces()
            {
                for( i=0;i<numberOfFaces;i++)
                {
                var img1 =document.createElement("img");
                img1.src = "smile.png";
                var topran = Math.random() * 400;
                var topran = Math.floor(topran);
                var leftran = Math.random() *400;
                var leftran = Math.floor(leftran);
                img1.style.top = topran + "px"; 
                img1.style.left = leftran + "px";
                theLeftSide.appendChild(img1);
                }
            }

        </script>
    </head>
    <body onload = "generateFaces()">

    </body>
</html>

Upvotes: 0

Views: 692

Answers (2)

pherris
pherris

Reputation: 17693

You can't style your smile image with img1 {position:absolute} in your CSS. Change your CSS to .smile {position:absolute} (a class selector) and set the class smile on img1.

var img1 =document.createElement("img");
img1.src = "smile.png";
img1.className = "smile";

Upvotes: 1

js1568
js1568

Reputation: 7032

img1 is not a valid CSS selector. Change it to just img or #leftSide img

Upvotes: 1

Related Questions