I was able to easily add text to my project using the following code:
const loadingText = $('#loading-text');
const text = "Your first sentence here"; // Your first sentence here
let i = 0;
const interval = setInterval(() => {
if (i === text.length) {
clearInterval(interval);
} else {
loadingText.text(loadingText.text() + text[i]);
i++;
}
}, 100); // Speed of animation (adjust as needed)
#loading-text {
font-size: 24px;
font-weight: bold;
text-align: center;
margin: 20px auto;
width: 50%;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="loading-text"></div>
Now the question that has come to me is, is there a way to display such text as HTML without tags (of course with the tag effect on the text)?
For example something like this:
const text = "lorem rerum <b style="color:#f00;">aperiam</b> maxime reiciendis";
In the text above, the word (aperiam) is placed between the tag and I have also given it a linear style.
By placing the above line in the text code, it is printed as follows:
lorem rerum <b style="color:#f00;">aperiam</b> maxime reiciendis
Is there a way to display the output as HTML?
3
Answers
You can’t add HTML one character at a time, since you need the
Instead of a single string, make
text
an array of strings, so you can wrap tags around each character to add the style and color.This works for tags that just add character style, since you get the same result wrapping each character with the tag as wrapping the tag around the whole string. It won’t work for more complex HTML like links.
As @Barmar said, you should use
$().html()
instead of.text()
. But even so, you should invest a little more effort into the character incrementing. Currently I am spelling out each character of each html tag that I am inputting. Ideally each tag should be treated as a whole and should not even be counted as a character.So, the following can only be a rough starting point:
Try using $().html() instead of using .text() because we cant add one character at a time in HTML