Home > Enterprise >  How to create a div positioned dynamically with JavaScript?
How to create a div positioned dynamically with JavaScript?

Time:10-28

I have a document where is a wrapper. This wrapper has two boxes. Box1 has div1 in which has some position (I can get the top position). On a click of a button the function returns the position of a div1, so that I'd be able to create div2 on the same level (pixels from top of the document), however something goes wrong. How should I approach it in order to create this div2 on the same level as div1 with JS? I've tried to do

const div2 = documentElement("div");
div2.style.position = "absolute";
div2.style.top = div1Top;
getElementById("box2").appendChild(div2);

but it doesn't work the way I want. Is there an issue with my whole project or just the code above should be written differently?

enter image description here

HTML:

<div id="wrapper" className='flex flex-row'>
   <div id="box1">
      <div id="div1">
      </div>
      <button type="button" onClick={create}>
         Create div2
      </button>
   </div>
   <div id="box2">
                    
   </div>
</div>

JS:

async function create() {
        const div2 = document.createElement("div");
        div2.style.position = "absolute";
        div2.style.top = top;
        document.getElementById("box2").appendChild(div2);
}

Thanks a lot in advance

CodePudding user response:

var button = document.getElementsByTagName("button")[0];

button.addEventListener('click', function(e) {
    var newdiv= document.createElement("div");
    newdiv.classList.add("outerbox");
    document.getElementsByClassName("wrapper")[0].appendChild(newdiv);
});
.wrapper {
  width: 100%;
  border: 1px solid blue;
  
}

.wrapper > div {
  display:inline-block;
}

.outerbox {
  width:120px;
  height:120px;
  border: 1px solid black;
}
<button>Append New Box</button>
</br>
</br>
</br>
<div class=wrapper>
  <div class=outerbox>
  </div>
</div>
</br>

CSS display should be all you need. Note that if the parent wrapper element is not wide enough to display your new child box horizontally, it will get displayed under the original one, or vertically. To ensure the new one is displayed on the same row, be sure the parent wrapper has enough width, which you can hard code in pixels. So, the short answer is one CSS rule as follows:

.wrapper > div {
  display: inline-block;
}

CodePudding user response:

The solution was pretty trivial. You need to ad "px" to top, because it needs an unit in order to properly define top position.

  • Related