Dynamically set the div positions on window load

186 Views Asked by At

I am trying to set the positions of the div tags I have in my web site. When the web page is loaded I have written a method to fetch the the existing div tags from my database. The reason why I do this is because the position of the div tags needs to be changed. Therefore the current div tag order is stored in the database. The function I have used to dynamically change the div tags are as below, This method is executed after invoking Window.onLoad()

function changeDivPosition (){

    getNewPosts().then(data=>{


        for(var i=0;i<data.newPosts.length;i++) {
            var divId=data.newPosts[i].id
            var divX=data.newPosts[i].xPosition;
            var divY=data.newPosts[i].yPosition;
            console.log(divId,divX,divY)
            var styles = `${'#'+divId}{
                           display:flex;
                           flex-wrap: wrap;
                           flex-direction:row;
                            align-content: space-around;
                            order: ${i};
                           };
                             }`
            $('#'+divId).offset({top:divY, left:divX});
            console.log(styles)
            var styleSheet = document.createElement("style")
            styleSheet.type = "text/css"
            styleSheet.innerText = styles
            document.head.appendChild(styleSheet)


        }

    })
}

The "data" array retrieves json data as follows,

 0: {_id: '61371ea7d14cd809b8cf3872',  id: 'mostPop', xPosition: 285, yPosition: -328.6000061035156}
1: {_id: '61371fe4d14cd809b8cf388c', id: 'sidebar-wrapper', xPosition: 0, yPosition: 0}
2: {_id: '61371ea9d14cd809b8cf387e',  id: 'itemDiscount', xPosition: 285, yPosition: 217.1999969482422}
3: {_id: '61371fe9d14cd809b8cf388e',  id: 'newArr', xPosition: 285, yPosition: 20}

This method manages to change the order of the div tags I want , but all the div tags are positioned together even though I set the X and Y coordinates. As shown in the below image,

enter image description here

I would like to understand what needs to be changed in order to properly render the layout as shown below enter image description here

1

There are 1 best solutions below

3
On

At least you are generating and appending an invalid CSS rule. Let's simplify the example just to the problem part:

var divId = 'mostPop'; 
var i = 1; 
var css = 
`${'#'+divId}{
    display:flex;
    flex-wrap: wrap;
    flex-direction:row;
    align-content: space-around;
    order: ${i};
    };
}`;
console.log(css);

Output:

#mostPop{
  display:flex;
  flex-wrap: wrap;
  flex-direction:row;
  align-content: space-around;
  order: 1;
  };
}

Can you see what's wrong with the CSS rule? An extra };

It should be:

var styles = 
   `${'#'+divId}{
      display:flex;
      flex-wrap: wrap;
      flex-direction:row;
      align-content: space-around;
      order: ${i};
    }`;