NickF
NickF

Reputation: 169

Javascript not outputting left angle bracket

I have some code which creates a 'typing text effect' on a page - i.e. javascript takes a string and outputs it on the screen in a way that makes it look like it is being typed. I took the code from a demo here.

The problem is that I want it to output html code, e.g. the output on the screen should be something like:

<html>
<body>
Something here etc etc...
</body>
</head>

In chrome, this works in a rather erratic fashion - sometimes it works perfectly, but other times it doesn't display the first left angle bracket, leaving me with the output of 'html>' rather than '<html>'. In safari, the left angle bracket doesn't display at all. I've tried various things, using '&lt;' instead of the bracket, using unicode, but that everything I do seems to end with the same result.

Here is a github gist of the code, and here is a bl.ocks page to showing it in action. I tried to make a jsfiddle but couldn't get it to run properly, sorry!

Any help is much appreciated, it's been driving me nuts. Cheers Nick

Upvotes: 1

Views: 1441

Answers (2)

Abraham
Abraham

Reputation: 20694

Instead of

$span.append(thisLine[letterIndex]);

try

$span.text($span.text() + thisLine[letterIndex]);

Or, per crush's comment below, you could do a string replace:

$span.append(thisLine[letterIndex].replace(/</g,'&lt;').replace(/>/g,'&gt;'));

This works because when you want to display HTML tags, you need to use &lt; and &gt; rather than just < and >, otherwise the browser thinks you're putting in an actual HTML tag, if that makes sense to you. The jquery text method automatically escapes the brackets for you, and in my second example, we're just doing a string replace before passing the string to append.

Upvotes: 2

symcbean
symcbean

Reputation: 48367

It looks as if the code appends '&lt;' as '&','l','t',';'. Not verified this but you might want to try:

 function typeLetter(lineIndex, letterIndex, $span, line, callback) {
   var thisLine = line;
   var thisLength = line.length;
   var chunk='';

   // add the letter
   chunk=thisLine[letterIndex];
   if ('&'==thisLine[letterIndex]) {
        for (var i=1; i<5; i++) {
           letterIndex++;
           chunk+=thisLine[letterIndex];
           if (';'==thisLine[letterIndex] || letterIndex>=thisLength-1) break;
        }
   }
   $span.append(chunk);
   ...

Upvotes: 1

Related Questions