0

The transform property will work in some instances, but what am I doing wrong in this instance:

  1. Making a span element and putting it in the innerHTML of a pre tag
  2. Span element has opacity: 0, and transform: 2s.
  3. Selecting this span element, and then changing opacity to 0.
  4. All this done in a function, shown below:

const lineText = document.getElementById("line-text");

function DisplayText() {
  lineText.innerHTML += "<span>TEXT!</span>";
  lineText.getElementsByTagName("span")[0].style.opacity = 1;
}
DisplayText();
span {
  opacity: 0;
  transition: 1s;
}
<pre id="line-text"></pre>

This always results in the element just appearing instantly. Any ideas what's wrong?

1 Answer 1

0

const lineText = document.getElementById("line-text");

function DisplayText() {
   lineText.innerHTML += "<span>TEXT!</span>";
   setTimeout(() => {
     lineText.getElementsByTagName("span")[0].style.opacity = 1;
   }, 10);
}
DisplayText();
    span {
            opacity: 0;
            transition: 1s;
        }
<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />

</head>

<body>

    <pre id="line-text"></pre>

</body>

</html>

I think if you add it in this way it will do what you want :

lineText.getElementsByTagName("span")[0].style = {
   transition:'1s',
   opacity:1
 };

or if it's still not working,I think that would because of by the time that javascript is appending "TEXT!" to lineText is applying style as well , so we need a small delay

 setTimeout(() => {
     lineText.getElementsByTagName("span")[0].style.opacity = 1;
   }, 10);

what I did is I let js to complete it's tasks in it's thread and then add style

Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't seem to work (element does not appear at all)
aha got it let me update my answer
This works, thanks! Is this really a limitation of JS, that it is too fast for itself?
yes, that's right
if it's what you were looking for please vote up and mark it as the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.