The transform property will work in some instances, but what am I doing wrong in this instance:
- Making a span element and putting it in the innerHTML of a pre tag
- Span element has opacity: 0, and transform: 2s.
- Selecting this span element, and then changing opacity to 0.
- All this done in a function, shown below:
HTML:
<pre id="line-text"></pre>
CSS:
span {
opacity: 0;
transition: 1s;
}
JS:
const lineText = document.getElementById("line-text");
function DisplayText() {
lineText.innerHTML = "<span>TEXT!</span>";
lineText.getElementsByTagName("span")[0].style.opacity = 1;
}
DisplayText();
This always results in the element just appearing instantly. Any ideas what's wrong?
CodePudding user response:
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