Skip to content
Advertisement

CSS transform property not working when it is triggered through JS function

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?

Advertisement

Answer

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

Advertisement