Question

I've the following function:

var index = 0;
var text = 'Hello world!';
function type() {
  document.getElementById('screen').innerHTML += text.charAt(index);
  index += 1;
  var t = setTimeout('type()',200);
}

I want to know if is possible to make it add a br tag between the words hello and world.

I tried like that: 'hello' + br tag + 'world'; but didn't work, probably because of the charAt.

Thanks

Was it helpful?

Solution

One possible approach:

var index = 0;
var text = 'Hello world!';
var textLength = text.length;
var elScreen = document.getElementById('screen');
(function type() {
  var charToType = text.charAt(index);
  if (charToType === ' ') {
    charToType = '<br />';
  }
  elScreen.innerHTML += charToType;
  index += 1;
  if (index < textLength) {
    setTimeout(type, 200);
  }
})();

Demo. The key idea is very simple: when the character to be processed next is whitespace, it's replaced with <br />.

Note two other changes here:

  • one can use function reference (instead of string) as setTimeout first param. In fact, one should use it this way.

  • unless there's a very big reason to do so, one should stop 'typing' that string when its end is reached - hence the index < textLength check.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top