EddNewGate EddNewGate - 5 months ago 16
Javascript Question

Appending a string with "<br>" tag doesn't work

I tried all methods possible and i simply can't add a break line inside a string which is stored in a variable and then used inside a specific function.

HTML code:

<body>
<p id="msg"></p>
</body>


Jquery code:

<script>
var showText = function (target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () { showText(target, message, index, interval); }, interval);
}
}
var x = "Hello there stranger!"+"<br>"+"How are you?";
$(function () {

showText("#msg", x, 0, 130);

});
</script>


It outputs the
<br>
tag as a string, instead to add a break line. Please help...

Answer

Your point is:

 [jQuery.append][1]

instead of:

 [jQuery.html][2]

I propose you:

var showText = function (target, message, index, interval) {
  if (index < message.length) {
    // if special character: append the break element
    if (message[index] == '\n') {
      index++;
      $(target).append('<br/>');
    } else {
      // else: append text to the html
      $(target).html($(target).html() + message[index++]);
    }
    setTimeout(function () {
      showText(target, message, index, interval);
    }, interval);
  }
}

// use a special character instead of the break element
var x = "Hello there stranger!\nHow are you?";

$(function () {
  showText("#msg", x, 0, 130);
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

<p id="msg"></p>

Comments