Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting HTML with JS

I'm just a bit stumped about something at the moment I have the following code which works as expected, everything is fine with it. However I would like to make some minor changes as I would like the following function to be able to insert html markup within the text itself i.e;

var str = "Let's get Future Ready!";
var split = str.split("");
var counter = 0;

var SI = setInterval(function() {

    var typeText = $('.typetext');
    typeText.append(split[counter]);
    counter++
    if(counter == str.length){clearInterval(SI)}

},100)

So at the moment, this function takes an array, split's and then using the setInterval method I have iterated over the string length. This allows for the text to look like it's being typed.

As you can see though, my initial value of str is 'var str = "Let's get Future Ready!";'

However I would like to add a break to my str value 'var str = "Let's get
Future Ready!"'

First of is it possible? Secondly, if anyone could offer me some advice I would be grateful, thanks.

like image 973
Troy Avatar asked Jun 08 '16 11:06

Troy


Video Answer


3 Answers

My suggestion is to replace the | character with <br> when doing the loop. Check it out here: https://jsfiddle.net/s04zbfcc/

var str = "Let's get|Future Ready!";
var split = str.split("");
var counter = 0;

var SI = setInterval(function() {

    var typeText = $('.typetext');

    typeText.append(split[counter] == '|' ? '<br>' : split[counter]);
    counter++

    if(counter == str.length) {
        clearInterval(SI)
    }

},100)
like image 124
Martin Gottweis Avatar answered Sep 30 '22 19:09

Martin Gottweis


So you want a line break in the HTML-Text you insert?

Insert a

<br />

into the array at the spot where you want the text to break.For inserting a element into an array look at the splice() function of javascript: http://www.w3schools.com/jsref/jsref_splice.asp

example with your code:

var str = "Let's get Future Ready!";
var split = str.split("");
var counter = 0;
split = split.splice(18, 0, "<br />");
like image 31
juli0r Avatar answered Sep 30 '22 19:09

juli0r


Check the below snippet. Explanation in comments

var str = "Let's get Future Ready!";
var split = str.split("");
var counter = 0;

var SI = setInterval(function() {

    var typeText = $('.typetext');
    typeText.append(split[counter]);
    counter++
    if(typeText.text()=="Let's get")//check the text and see if it  has Let's get
      typeText.append("<br/>");//if yes append br there
    if(counter == str.length){
      clearInterval(SI);
    }

},100)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="typetext"></div>
like image 29
Guruprasad J Rao Avatar answered Sep 30 '22 17:09

Guruprasad J Rao