Reputation: 51
I have a function that appends a text into the div
with some color effect.
I want to make the text appearing word after word. (But I need this effect only on the text of second function's parameter "str", the "who" have to appear normal.
I found an example code of the effect that I need, but I don't get how to make both functions work together as I want.
JS:
// my function
var showText = function(who, str) {
if(str !== "") {
$("#storyBoard").append("<p><span style='color:#323232;'>" + who.name + ": " + "</span>" + str + "</p>");
};
};
showText(somObj, "The text i want to append on the page when calling the function");
// the function i want to add into my first function
$(function() {
var a = new String;
a = $('.text_cont_inner').text();
$('.text_cont_inner').text('');
var c = a.length;
j = 0;
setInterval(function() {
if(j < c) {
$('.text_cont_inner').text($('.text_cont_inner').text() + a[j]);
j = j + 1;
} else {
$('.text_cont_inner').removeClass('after')
}
}, 100);
});
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>MacroG0D - My first game</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src ='Js/main.js' type="text/javascript"> </script>
</head>
<body>
<div id = "storyBoard">
<h1> Star Wars - Healing <br>The Breach:<hr></h1>
<p class="intro">A long time ago, in a galaxy far, far away</p>
<p> Welcome to the virtual pseudo-reality. Are you ready to start this journey? </p>
</div>
<input type="text" id ="myInput" placeholder="Type the command here" name="myInput" autofocus autocomplete='off'/>
<button id="btn" type="submit"> Enter </button>
</body>
</html>
Upvotes: 2
Views: 1644
Reputation: 2746
Try this :)
var showText = function(who, str) {
if(!str){
return;
}
var textNode = $("#storyBoard") // take container
.append("<p><span style='color:#323232;'>" + who.name + ": </span><span></span></p>") // add contents
.find("p span:last-сhild")[0]; // select last <span> to put str value into
var words = str.split(" "); // break a string on words
var intervalId = setInterval(function() { // set new interval and remember it's ID
if (!words.length) { // no words left in array
return clearInterval(intervalId); // stop running interval and exit
}
textNode.innerText += " " + words.shift(); // add space and next word
}, 100); // milliseconds between word insertions
};
Upvotes: 1