Игор Рајачић Игор Рајачић - 6 months ago 34
Javascript Question

jQuery create DIV with dynamic ID and defined CSS attributes (which define look and position of that div)

I have some basic code here. It just creates a div element to a certain defined position, and the ID is not dynamic.

var i=1;
while (i<=6)
{
jQuery('<div/>', {
id: 'karta_back'
// I don't know how to insert CSS here
}).appendTo('#igrac1');

++i;
}


The problem is with dynamic ids. With css, I don't know how to define the CSS inside that function. For this example, I used the internal CSS that is defined somewhere in the document. With the position, I suppose that cards need to be CSS absolute positioned to perform like i would like.

This is the result that I have with this simple code I wrote:
http://dl.dropbox.com/u/2849320/achieved.png

This is what i want to achieve:
http://dl.dropbox.com/u/2849320/want%20to%20achieve.jpg

How can I do this?

Answer

If I understand you correctly just, use the style attribute, you don't need a dynamic id:

var i = 1;
while (i <= 6) {
    jQuery('<div/>', {
        id: 'karta_back' + i, //this will add serial number to end of ID
        //this is a good starting point for what you're trying to accomplish
        style: 'position:absolute;margin-left:' + i * 20 + 'px;z-index:' + i;
     }).appendTo('#igrac1');

     i++;
}

So you can select them like:

$('#karta_back1', '#karta_back2'); //selects first two

Here is a jsFiddle example of it working, with a crappy card image.

Comments