skip to Main Content

When I try to append a child to an element, it increases the offset height of the element. Even when a transition is used, it just appends the child instantly. I just want to make a transition for that.

const p = document.createElement("p");
p.innerText = "Sample text";
document.getElementById("main").appendChild(p);
div#main {
  transition: all 0.5s ease;
}
<div id="main"></div>

2

Answers


  1. You need to append the element as invisible/hidden, then animate its transition to being visible. Also note that your current transition is targeting the #main element, which is always in the DOM as soon as the page loads, not the p element you dynamically create.

    Below is a working example of how to do this with an opacity fade-in, although any method would work; height/width swipes, text scrolling, blurs etc.

    Note that the timeout is required to delay the removal of the class which hides the element until after it has been initially rendered to the DOM:

    const p = document.createElement("p");
    p.classList.add('appended');
    p.innerText = "Sample text";
    document.getElementById("main").appendChild(p);
    
    setTimeout(() => {
      p.classList.remove('appended');
    }, 25);
    div p {
      opacity: 1;
      transition: opacity 0.5s ease;
    }
    
    div p.appended {
      opacity: 0;
    }
    <div id="main"></div>
    Login or Signup to reply.
  2. As I mentioned earlier and following the same idea of @Rory McCrossan you can use either height or font-size to set the transition as well

    const p = document.createElement("p");
    p.innerText = "Sample text";
    document.getElementById("main").appendChild(p);
    setTimeout(()=>{p.classList.add('initial')},100)
    setInterval(()=>{console.log(p.offsetHeight)},0.5)
    p{
    font-size : 0px;
    transition: font-size 2s ease;
    }
    
    .initial{
    font-size: 30px;
    transition: font-size 2s ease;
    }
    <div id="main"></div>
    const p = document.createElement("p");
    
    document.getElementById("main").appendChild(p);
    setTimeout(()=>{p.classList.add('initial')},100)
    setTimeout(()=>{p.innerText = "Sample text"},1000)
    setInterval(()=>{console.log(p.offsetHeight)},0.5)
    p{
    height : 0px;
    transition: height 1s ease;
    background-color:yellow;
    }
    
    .initial{
    height: 30px;
    transition: height 1s ease;
    }
    <div id="main"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search