Run Javascript only after div is 'shown', display:block - javascript

I am using this JavaScript function to toggle between divs:
function show(shown, hidden) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
return false;
}
I and trying a little text animation, but the problem is that the text animation is supposed to start when I get to page 2 from page 1. However the text animation from javascript runs as soon as i load the page and I am still on page 1.
here is the full html page:
<!DOCTYPE html>
<html>
<head>
<script>
function show(shown, hidden) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
return false;
}
</script>
</head>
<body>
<div id="Page1">
Content of page 1
Show page 2
</div>
<div id="Page2" style="display:none">
<div id="typedtext"></div>
<script>
var aText = new Array(
"hey man",
"how are you",
"how is it going"
);
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
function typewriter()
{
sContents = ' ';
iRow = Math.max(0, iIndex-iScrollAt);
var destination = document.getElementById("typedtext");
while ( iRow < iIndex ) {
sContents += aText[iRow++] + '<br />';
}
destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
if ( iTextPos++ == iArrLength ) {
iTextPos = 0;
iIndex++;
if ( iIndex != aText.length ) {
iArrLength = aText[iIndex].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", iSpeed);
}
}
window.onload = typewriter();
</script>
Show page 1
</div>
</body>
</html>
How can i make it so that the javascript function starts running only after i show the page 2 div after i have clicked to go to page 2?

You should only execute the typewriter function if the element to be shown has an id of "Page2".
function show(shown, hidden) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
if(shown === 'Page2'){
typewriter();
}
return false;
}
Live Example:
<!DOCTYPE html>
<html>
<head>
<script>
function show(shown, hidden) {
document.getElementById(shown).style.display = 'block';
document.getElementById(hidden).style.display = 'none';
if (shown === 'Page2') {
typewriter();
}
return false;
}
</script>
</head>
<body>
<div id="Page1">
Content of page 1
Show page 2
</div>
<div id="Page2" style="display:none">
<div id="typedtext"></div>
<script>
var aText = new Array(
"hey man",
"how are you",
"how is it going"
);
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
function typewriter() {
sContents = ' ';
iRow = Math.max(0, iIndex - iScrollAt);
var destination = document.getElementById("typedtext");
while (iRow < iIndex) {
sContents += aText[iRow++] + '<br />';
}
destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
if (iTextPos++ == iArrLength) {
iTextPos = 0;
iIndex++;
if (iIndex != aText.length) {
iArrLength = aText[iIndex].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", iSpeed);
}
}
</script>
Show page 1
</div>
</body>
</html>

so fixed - and tested in codepen.
problem was the window.load part - it calls as soon as the WINDOW loads... not page2, since page2 is just a div turning on and off, it's not a new page.
the addEventListener just tends to be clearer and cleaner to write in - and it is a better point to combine function outputs - the onClick="" is meh - addEventListener is where it's at.
attaching a event handler -housing an annon function containing special logic for page2 is what you are after it looks like. code is below.
<html>
<body>
<div id="Page1"> Content of page 1
Show page 2
</div>
<div id="Page2" style="display:none">
<div id="typedtext"></div>
Show page 1
</div>
</body>
</html>
function show(shown, hidden) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
return false;
}
const link1=document.getElementById("link1");
const link2=document.getElementById("link2");
link1.addEventListener("click", function(){
show('Page2','Page1');
typewriter();
});
link2.addEventListener("click", function(){
show('Page1','Page2');
});
var aText = new Array(
"hey man",
"how are you",
"how is it going"
);
var iSpeed = 1000; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
function typewriter()
{
console.log("typing");
sContents = ' ';
iRow = Math.max(0, iIndex-iScrollAt);
var destination = document.getElementById("typedtext");
while ( iRow < iIndex ) {
sContents += aText[iRow++] + '<br />';
}
destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) + "_";
if ( iTextPos++ == iArrLength ) {
iTextPos = 0;
iIndex++;
if ( iIndex != aText.length ) {
iArrLength = aText[iIndex].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", iSpeed);
}
}

instead of
onclick="return show('Page2','Page1');"
use
onclick="function() {return show('Page2','Page1')}"

Simply delete the window.onload part and put typewriter() right before return false in your show function

Related

How to delete the text and print new text letter by letter by clicking once after printing a text letter by letter

I'm quite a newcomer to HTML Front End, and now working on the school project to make a simple text interactive game, but I'm now stuck by this problem when I'm trying to make the interface better.
I can now implement this function by clicking the text button once to clearout the former text and clicking twice to print new text, but I want to realize these two effects at the same time by only clicking once.
I want to fix this problem by optimizing the function replace(),but it doesn't seem to work ,since the new text I want to print simply appear for about 50ms and disappear but I don't really know why.It seems to be something wrong with the function setInterval(),
Is there any possible ways to optimize it?
(the following is the code)
<html>
<head>
<meta charset="utf-8">
<title>Part1-intro2</title>
<link href="../css/main.css" rel="stylesheet" type="text/css"/>
<script src="../js/jquery-1.11.1.min.js"></script>
<script src="../js/Main.js"></script>
<script>
window.onload=function()
{
var temp = document.getElementsByClassName('dialog')[0];
var text = 'test text1';/*这里改对话内容*/
var len = text.length;
var timer = null;
var index = 0;
timer = setInterval(function(){
if(index == len){
clearInterval(timer);
}
temp.innerHTML+=text.charAt(index++);
},125);
}
function goForward()
{
window.location.assign("Sc2.html");
}
var t=0;
function replace()
{ if(t==0)
{
var temp = document.getElementsByClassName('dialog')[0];
var text = '';/*这里改对话内容*/
var len = text.length;
var timer = null;
var index = 0;
timer = setInterval(function(){
if(index == len){
clearInterval(timer);
}
temp.innerHTML=text.charAt(index);
},10);
t++;
}
else if(t==1)
{
temp = document.getElementsByClassName('dialog')[0];
text1 = 'test text1';
len = text1.length;
timer = null;
index = 0;
timer = setInterval(function(){
if(index == len){
clearInterval(timer);
}
temp.innerHTML+=text1.charAt(index++);
},50);
t++;
}
else if(t==2)
{
var temp = document.getElementsByClassName('dialog')[0];
var text = '';/*这里改对话内容*/
var len = text.length;
var timer = null;
var index = 0;
timer = setInterval(function(){
if(index == len){
clearInterval(timer);
}
temp.innerHTML=text.charAt(index);
},10);
t++;
}
else if(t==3)
{
var temp = document.getElementsByClassName('dialog')[0];
var text1 = 'test text2';/*这里改对话内容*/
var len = text1.length;
var timer = null;
var index = 0;
timer = setInterval(function(){
if(index == len){
clearInterval(timer);
}
temp.innerHTML=text1.charAt(index++);
},50);
t++;
}
else if(t==4)
{
goForward();
}
}
</script>
<style>
body {
background: url(../images/bg_通学路2.png) no-repeat;
background-size:100% 100%;;
}
</style>
</head>
<body background="../images/bg_通学路2.png">
<div>
<button class="basbt" id="ico-home" onclick="toHome()"></button>
<button class="basbt" id="ico-back" onclick="Back()"></button>
<button class="basbt" id="ico-save" onclick="Savegame()"></button>
</div>
<div class="Text" onclick="replace()">
<span class="cover1"></span>
<div class="dialog"></div>
<div class="Guide">>></div>
</div>
</body>
</html>

Create "blinking" caret effect for javascript "typing"

So I currently have some javascript code that creates a "typing" effect. During the typing, there is a caret at the end that mimics the caret type when typing into a console. When the typing has finished, I'd like for the caret to begin blinking, just as it would within a console. Here is the code used for it:
html:
<div id="typedtext"></div>
javascript:
// set up text to print, each item in array is new line
var arrText = new Array(
"This is an example of some,",
"typed text."
);
var speed = 60; // time delay of print out
var index = 0; // start printing array at this posision
var arrLength = arrText[0].length; // the length of the text array
var scrollAt = 20; // start scrolling up at this many lines
var textPos = 0; // initialise text position
var contents = ''; // initialise contents variable
var row; // initialise current row
function typewriter()
{
contents = ' ';
row = Math.max(0, index-scrollAt);
var destination = document.getElementById("typedtext");
while ( row < index ) {
contents += arrText[row++] + '<br />';
}
destination.innerHTML = contents + arrText[index].substring(0, textPos) + "█";
if ( textPos++ == arrLength ) {
textPos = 0;
index++;
if ( index != arrText.length ) {
arrLength = arrText[index].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", speed);
}
}
typewriter();
Is this possible?
You can add a few CSS scripts to add blinking effect to the caret. Move the █ inside a <span> and add .blink class to it.
// set up text to print, each item in array is new line
var arrText = new Array(
"This is an example of some,",
"typed text."
);
var speed = 60; // time delay of print out
var index = 0; // start printing array at this posision
var arrLength = arrText[0].length; // the length of the text array
var scrollAt = 20; // start scrolling up at this many lines
var textPos = 0; // initialise text position
var contents = ''; // initialise contents variable
var row; // initialise current row
function typewriter() {
contents = ' ';
row = Math.max(0, index - scrollAt);
var destination = document.getElementById("typedtext");
while (row < index) {
contents += arrText[row++] + '<br />';
}
destination.innerHTML = contents + arrText[index].substring(0, textPos) + "<span class='blink'>█<span>";
if (textPos++ == arrLength) {
textPos = 0;
index++;
if (index != arrText.length) {
arrLength = arrText[index].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", speed);
}
}
typewriter();
.blink {
animation: blink-animation 1s steps(5, start) infinite;
-webkit-animation: blink-animation 1s steps(5, start) infinite;
}
#keyframes blink-animation {
to {
visibility: hidden;
}
}
#-webkit-keyframes blink-animation {
to {
visibility: hidden;
}
}
<div id="typedtext"></div>

I need time delay in every loop iteration. Also let me know alternate of bold <b>

Below is the code for typewriting. After all lines are written, I need them to stay for some seconds and the then disappear for the second loop and so on. Also, let me know what is the alternate of bold <b> for making specific words bold as tags do not work with string. They show < on display during execution. Thanks.
<!DOCTYPE html>
<html>
<body>
<pre id="typing" </pre>
<script>
for (let i=0; i<10; i++) {
task(i);
}
function task(i) {
setTimeout(function() {
// Add tasks to do
var typeString = ['• I \r m Mr.Frits.\n• and I love Pakistan...:)'];
var i = 0;
var count = 0
var selectedText = '';
var text = '';
(function type() {
if (count == typeString.length) {
count = 0;
}
selectedText = typeString[count];
text = selectedText.slice(0, ++i);
document.getElementById('typing').innerHTML = text.fontsize(6);
document.getElementById('typing').style.fontFamily = "monospace";
document.getElementById("typing").style.color = "black";
document.getElementById("typing").style.fontWeight = "normal";
if (text.length === selectedText.length) {
count++;
i = 0;
}
/* SOLUTION : wait two seconds when new line */
if (typeString[0][i-1] == '\n') {
setTimeout(type, 1000);
} else {
setTimeout(type, 100);
}
}());
}, 1000);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<pre id="typing" </pre>
<script>
for (let i=0; i<10; i++) {
task(i);
}
function task(i) {
setTimeout(function() {
// Add tasks to do
var typeString = ['• I \r m Mr.Frits.\n• and I love Pakistan...:)'];
var i = 0;
var count = 0
var selectedText = '';
var text = '';
(function type() {
if (count == typeString.length) {
count = 0;
}
selectedText = typeString[count];
text = selectedText.slice(0, ++i);
document.getElementById('typing').innerHTML = text.fontsize(6);
document.getElementById('typing').style.fontFamily = "monospace";
document.getElementById("typing").style.color = "black";
document.getElementById("typing").style.fontWeight = "normal";
if (text.length === selectedText.length) {
count++;
setTimeout(function(){i = 0;},3000) /*Added this part*/
}
/* SOLUTION : wait two seconds when new line */
if (typeString[0][i-1] == '\n') {
setTimeout(type, 100);
} else {
setTimeout(type, 100);
}
}());
}, 1000);
}
</script>
</body>
</html>
alternate of <b> is <strong>.
you can use css properties to bold your text either. Example:(font-weight:900;)

How to include hyperlink within Javascript string array?

I'm trying to add a hyperlink to the string -- and I've attempted using both .link and .innerHTML - tho I think I may be misunderstanding what I ought to do (very new to this). Below is my code:
<div id="typedtext"></div>
<script type="text/javascript">
// set up text to print, each item in array is new line
var aText = new Array(
"Hi, I'm Krishaan!", "A few words, wish I could add a link here", "Here are
some words." ,"thanks a million for any help -- click here for more."
);
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
function typewriter()
{
sContents = ' ';
iRow = Math.max(0, iIndex-iScrollAt);
var destination = document.getElementById("typedtext");
while ( iRow < iIndex ) {
sContents += aText[iRow++] + '<br />';
}
destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) +
"_";
if ( iTextPos++ == iArrLength ) {
iTextPos = 0;
iIndex++;
if ( iIndex != aText.length ) {
iArrLength = aText[iIndex].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", iSpeed);
}
}
As with standard HTML, you can simply wrap your desired link in <a href='location'>text</a> whilst outputting it through your JavaScript:
// set up text to print, each item in array is new line
var aText = new Array("Hi, I'm Krishaan!", "A few words, wish I could add a link here", "Here are some words.", "thanks a million for any help--click <a href='http://www.google.com'>here</a> for more.");
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
function typewriter() {
sContents = ' ';
iRow = Math.max(0, iIndex - iScrollAt);
var destination = document.getElementById("typedtext");
while (iRow < iIndex) {
sContents += aText[iRow++] + '<br />';
}
destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) +
"_";
if (iTextPos++ == iArrLength) {
iTextPos = 0;
iIndex++;
if (iIndex != aText.length) {
iArrLength = aText[iIndex].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", iSpeed);
}
}
typewriter();
<div id="typedtext"></div>
Note that as your array uses double quotes, your hyperlink will need to use single quotes!

Tried writing a loop statement that prints out my playlist, but my browser just infinitely loops instead

So, I am to write a loop statement that prints out my playlist, but my browser just infinitely loops instead of loading the text and the content. How could I adjust my code to do that?
<!DOCTYPE html>
<html>
<head>
<title>9. Looping Statements in Javascript</title>
</head>
<body>
<h1>9. Looping Statements in Javascript</h1>
<div id="container"></div>
<div id="playlist"></div>
<script>
var playlist = [];
playlist[0] = "Willy Wesly";
playlist[1] = "Childish Gambino";
playlist[2] = "Chance The Rapper";
playlist[3] = "Travi$ Scott";
playlist[4] = "Yeezy";
// while
var i = 0;
while (i < playlist.length); {
var element = document.getElementById('playlist').innerHTML = playlist;
element.innerHTML = 'Now Playing: ' + playlist[i], i++;
container.appendChild(element);
}
</script>
</body>
</html>
Try this Remove the semicolon after the while closing brackets:
var i = 0;
while (i < playlist.length) {
var element = document.getElementById('playlist').innerHTML = playlist;
element.innerHTML = 'Now Playing: ' + playlist[i], i++;
container.appendChild(element);
}
You don't need to append the element, it's already part of the dom. just add to its innerHTML, (The br's are just how I think it would look prettiest)
var i = 0;
var element = document.getElementById('playlist');
element.innerHTML = 'Now Playing:<br/>';
while (i++ < playlist.length) {
element.innerHTML += playlist[i] + '<br/>';
}

Categories