Sina
Sina

Reputation: 71

Styling elements created dynamically

i am a newbee so sorry if my question is basic. i have written a code (with the help of the forum offcourse) where by clicking on an image another one appears and when you click on the new one, again another one appears and so on. the problem is i can not add an style to the code and make the images appear in different positions to make a layout. can anyone here help me? thank you so much

    <meta charset="utf-8">
    <title> COOPER BLACK </title>
    <link rel="stylesheet" type="text/javascript" href="style.css" media="screen">

</head>

<div class="container">
<script type="text/javaSCRIPT">

        var i = 1

        function imageClick() {
            if (! this.alreadyClicked)
                {
                addimage();
                counter();
                this.alreadyClicked = true;
                }
        }

        function addimage() {
            var img = document.createElement("img");
            img.src = "images/d"+i+".jpg";
            img.onclick = imageClick;
            document.body.appendChild(img);
        }

        function counter() {
            i = i + 1
        }

</script>

 <div class="first">
         <input class="first" type="image" src="images/d0.jpg" onclick="imageClick();">

        </div>

</div>

Upvotes: 2

Views: 219

Answers (1)

5unkEn
5unkEn

Reputation: 78

Try setting the class attribute this way

img.setAttribute("class", "YourClassName");

Then apply the style to YourClassName in a CSS file/style tag. (Might also want to call the script after you load the CSS) Like so

.YourClassName { /* style here */ }

Edit: You can also check if the elements are rendered well (the HTML tags have the class names and onClick methods) using the console (press F12 on the page)

Upvotes: 2

Related Questions