3gwebtrain
3gwebtrain

Reputation: 15297

Element appending with and without scroll varies

I have 2 button, one in top another in the bottom. when I click the top button it works fine. when i scroll down to bottom button and click the button again ( same function ) it appends the element with some where. I am calculating the top position from absolute way. getting the relation ship with body.

so how to handle this kind of scenario?

Live demo

Js code :

const h1All = document.getElementsByTagName("h1");

function addElement() {
  let div = document.createElement('div');
  div.innerText = "I am here";
  div.style.border = "1px solid green";
  div.style.position = "absolute";
  let h1 = h1All[0];
  h1.style.border = "1px solid red";
  let parentPos =  h1.getBoundingClientRect();
  console.log(parentPos)
  document.body.appendChild(div);
  div.style.top = parentPos.y + parentPos.height + "px";
}

HTML:

 <h1>Hello Plunker!</h1>
    <div class="mydiv">some div info goes here
      <button onclick="addElement()">Click Me </button> //works fine.
    </div>
    <button onclick="addElement()">Click Me </button> //it's not. after scroll down!!

the second button appends the element some where. what is the correct way to calculation do we have to do here?

Thanks in advance.

const h1All = document.getElementsByTagName("h1");

function addElement() {
  let div = document.createElement('div');
  div.innerText = "I am here";
  div.style.border = "1px solid green";
  div.style.position = "absolute";
  let h1 = h1All[0];
  h1.style.border = "1px solid red";
  let parentPos =  h1.getBoundingClientRect();

  document.body.appendChild(div);
  div.style.top = parentPos.y + parentPos.height + "px";
}
.mydiv{
  border: 1px solid green;
  height: 600px; 
}
 <h1>Hello Plunker!</h1>
    <div class="mydiv">some div info goes here
      <button onclick="addElement()">Click Me </button>
    </div>
    <button onclick="addElement()">Click Me </button>

Upvotes: 0

Views: 46

Answers (1)

vqf
vqf

Reputation: 2628

If you want absolute positioning, you need to take scrolling into account. You can do that with window.scrollY. Notice the change at the last line of addElement:

const h1All = document.getElementsByTagName("h1");

function addElement() {
  let div = document.createElement('div');
  div.innerText = "I am here";
  div.style.border = "1px solid green";
  div.style.position = "absolute";
  let h1 = h1All[0];
  h1.style.border = "1px solid red";
  let parentPos =  h1.getBoundingClientRect();

  document.body.appendChild(div);
  div.style.top = parentPos.y + parentPos.height + window.scrollY + "px";
}
.mydiv{
  border: 1px solid green;
  height: 600px; 
}
<h1>Hello Plunker!</h1>
    <div class="mydiv">some div info goes here
      <button onclick="addElement()">Click Me </button>
    </div>
    <button onclick="addElement()">Click Me </button>

Upvotes: 1

Related Questions