'How to create element with absolute position
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';
Solution 1:[1]
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;
}
Solution 2:[2]
<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>
Solution 3:[3]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marian150 |
| Solution 2 | Dip Kumar |
| Solution 3 | ash |
