Home > Software design >  How to create element with absolute position
How to create element with absolute position

Time:02-20

I want Date to appear above Second section. plz guide how to achieve it

    var sectionTwo = document.getElementById("sectionTwo");
    var x = sectionTwo.getBoundingClientRect();
    var b = document.createElement("div");
    b.style.position = 'fixed';
    b.innerHTML = new Date();
    document.body.appendChild(b);
    b.style.top = (x.top - b.style.height)   'px';

enter image description here

CodePudding user response:

One way to do it is like this:

HTML code:

<div id="sectionTwo">

</div>

JS code:

var sectionTwo = document.getElementById("sectionTwo");
var b = document.createElement("div");
b.innerHTML = new Date();
sectionTwo.insertAdjacentElement("beforebegin", b);

CSS code (just to for visualization):

#sectionTwo {
  width: 80%;
  height: 50px;
  background-color: gray;
}

CodePudding user response:

Maybe this could help you better.

var sectionTwo = document.getElementById("sectionTwo");
var b = document.createElement("div");
b.innerHTML = new Date();
sectionTwo.insertAdjacentElement("beforebegin", b);
#sectionTwo {

  height: 35px; width:35px;
  background-color: pink;
}
<div id="sectionTwo">

</div>

CodePudding user response:

<div>
<div style="height:800px;"></div>
<div id="sectionOne">First Section</div>
<div id="sectionTwo">Second Section</div>
<button onclick="showDate();">toggle</button></div>



<script> function showDate() {
    var sectionTwo = document.getElementById("sectionTwo");
    var x = sectionTwo.getBoundingClientRect();
    var b = document.createElement("div");
    b.style.position = 'absolute';
    b.innerHTML = new Date();
    document.body.appendChild(b);
    b.style.bottom = 0;
    b.style.top = (x.top - b.offsetHeight)   'px';
}</script>

enter image description here

  • Related