I am making an escape room for my website, I have made a few clickable objects that will display a text. My question is, how do I make text go away after clicking on another clickable item? Everything else in my code works just how I like it except for the text part. Please help
Here is what I have so far.
var hasBluekey = false;
var doorknob = "locked"
var comboLock = "locked"
function tryDoor() {
console.log("You clicked the door");
}
function lookhelp() {
console.log("You clicked on help");
let text = "Who needs help?";
document.getElementById("thehelp").innerHTML = text;
}
function lookClue() {
console.log("You clicked on the clue");
let text = "Hmm, there are letters and numbers circled...";
document.getElementById("theclue").innerHTML = text;
}
function moveTable() {
console.log("You clicked on the table");
let text = "You carefully move away the table with the broken vase";
document.getElementById("thetable").innerHTML = text;
document.getElementById("table").style.display = "none";
}
function tryDoorknob() {
console.log("You clicked the doorknob")
if (hasBluekey == true) {
doorknob = "unlocked";
alert("The doorknob is now unlocked");
checkRoom();
} else {
alert("You need a key");
}
}
function tryComboLock() {
console.log("You clicked the combo lock");
var comboTry = prompt("You enter the combination...");
if (comboTry == "AV70") {
comboLock = "unlocked";
alert("The combination was correct");
checkRoom();
} else {
alert("The combination was incorrect");
}
}
function grabBluekey() {
console.log("You clicked the blue key");
hasBluekey = true;
alert("You picked up the key");
document.getElementById("bluekey").style.display = "none";
}
function checkRoom() {
if (doorknob == "unlocked") {
if (comboLock == "unlocked") {
document.getElementById("next").style.visibility = "visible";
} else {
alert("You push on the door but still need a combination");
}
} else {
alert("You try to turn the door knob but is still locked");
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="room">
<img id="door" src="door1.png" onclick="tryDoor()">
<img id="doorknob" src="doorknob1.png" onclick="tryDoorknob()">
<img id="comboLock" src="comboLock.png" onclick="tryComboLock()">
<img id="bluekey" src="blue_key.png" onclick="grabBluekey()">
<img id="clue" src="clue.png" onclick="lookClue()">
<img id="help" src="help.png" onclick="lookhelp()">
<img id="bloodMark" src="bloodMark.png">
<img id="table" src="table.png" onclick="moveTable()">
<img id="window" src="window.png">
<p id="thehelp"></p>
<p id="theclue">
</P>
<p id="thetable"></p>
</div>
<button id="next" onclick="window.location.href
='room2.html';">Proceed</button>
</body>
</html>
Your request seem impossible with an easy answer because you are displaying the text with console.log() I don't think it is possible to update individual lines of output in the console. It is not mentioned anywhere in the documentation. Your easy way out is to display the message or text in a separate element and update that element with the latest text as required. Here is how your code should look like now.
in your html add this code where you want the message to be displayed and style it however you want
<p id="text_message"></p>
And in your javascript code you should replace the console.log("your message"); to this text_message.innerHTML = "your message";
var hasBluekey = false;
var doorknob = "locked"
var comboLock = "locked"
function tryDoor() {
text_message.innerHTML = "You clicked the door";
}
function lookhelp() {
text_message.innerHTML = "You clicked on help";
let text = "Who needs help?";
document.getElementById("thehelp").innerHTML = text;
}
function lookClue() {
text_message.innerHTML = "You clicked on the clue";
let text = "Hmm, there are letters and numbers circled...";
document.getElementById("theclue").innerHTML = text;
}
function moveTable() {
text_message.innerHTML = "You clicked on the table";
let text = "You carefully move away the table with the broken vase";
document.getElementById("thetable").innerHTML = text;
document.getElementById("table").style.display = "none";
}
function tryDoorknob() {
text_message.innerHTML = "You clicked the doorknob";
if (hasBluekey == true) {
doorknob = "unlocked";
alert("The doorknob is now unlocked");
checkRoom();
} else {
alert("You need a key");
}
}
function tryComboLock() {
text_message.innerHTML = "You clicked the combo lock";
var comboTry = prompt("You enter the combination...");
if (comboTry == "AV70") {
comboLock = "unlocked";
alert("The combination was correct");
checkRoom();
} else {
alert("The combination was incorrect");
}
}
function grabBluekey() {
text_message.innerHTML = "You clicked the blue key";
hasBluekey = true;
alert("You picked up the key");
document.getElementById("bluekey").style.display = "none";
}
function checkRoom() {
if (doorknob == "unlocked") {
if (comboLock == "unlocked") {
document.getElementById("next").style.visibility = "visible";
} else {
alert("You push on the door but still need a combination");
}
} else {
alert("You try to turn the door knob but is still locked");
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p id="text_message" style="background-color:grey;color:white;"></p>
<div id="room">
<img id="door" src="door1.png" onclick="tryDoor()">
<img id="doorknob" src="doorknob1.png" onclick="tryDoorknob()">
<img id="comboLock" src="comboLock.png" onclick="tryComboLock()">
<img id="bluekey" src="blue_key.png" onclick="grabBluekey()">
<img id="clue" src="clue.png" onclick="lookClue()">
<img id="help" src="help.png" onclick="lookhelp()">
<img id="bloodMark" src="bloodMark.png">
<img id="table" src="table.png" onclick="moveTable()">
<img id="window" src="window.png">
<p id="thehelp"></p>
<p id="theclue">
</P>
<p id="thetable"></p>
</div>
<button id="next" onclick="window.location.href
='room2.html';">Proceed</button>
</body>
</html>
You could try to use ANSI escape codes -- they are really useful for formatting text in a terminal after it's been printed. For this you would want to use cursor controls and erase functions. these are from this tutorial, which was very helpful for a project I made a while ago. Not all of them work on every platform (e.g. replit, not sure if anyone actually uses that though) but overall it's a good system.
example:
console.log("normal text");
//bold, red foreground
console.log("\u001B[1;31m");
console.log("edited text");
(example from the tutorial)
I'm bad at making examples, but I found the two aforementioned sections to be good for quick reference. To truly comprehend how to use it, I suggest that you read through the whole thing.
Related
I'm a beginner working on a trivia app, and I'm having a heck of a time getting the questions to iterate properly. I've tried things multiple different ways. Here is my current configuration.
The questions are iterated by the pullQuestions() function. This function pulls from an array called question.
The pullQuestions() function is run when the startbutton is clicked and when the submitA button is clicked. These buttons run either startGame() or submitA() respectively.
Please note, I have not yet implemented score tracking so the expectation of the submit button is currently limited to pulling the next question.
Question HTML
<div id="gameArea" class="questionbox" style="display: none;">
<div class="questionarea">
<h2 id="headerQ">Question Number</h2>
<p id="content">Question Text</p>
</div>
<div class="answerarea">
<!-- This can be ignored. This is where my options are but I'm not using them in my code yet -->
</div>
<button id="submitA" class="submitA" onClick="submitA()">Submit</button>
</div>
startGame() JavaScript (This works as expected)
function startGame(){
document.getElementById("startArea").style.display = "none";
document.getElementById("gameArea").style.display = "block";
question.id = 0;
pullQuestions();
console.log("startgame() Executed", question.id);
console.log(question[0], question[1]);
}
Question Array* (Set as a Global Variable)
function select1() {
if (op1.className == "selectionFalse") {
document.getElementById("op1").className = "selectionTrue";
document.getElementById("op2").className = "selectionFalse";
document.getElementById("op3").className = "selectionFalse";
document.getElementById("op4").className = "selectionFalse";
console.log("selected1()", "If Condition", op1.className);
}
else {
document.getElementById("op1").className = "selectionFalse";
}
}
submitA() JavaScript (Does not iterate through the Array but does increase the id attribute)
function submitA() {
question.id++;
console.log("submitA() Run)", "Question ID: ", question.id, headerQ, content);
}
*pullQuestions() JavaScript (This is run when the two above functions are run, but I only see results when it runs as part of the startGame() function.
function pullQuestions() {
if (question.id == 0) {
document.getElementById("headerQ").innerHTML = question[0].headerQ;
document.getElementById("content").innerHTML = question[0].content;
console.log("pullQuestions() Executed");
console.log("Variables: ", "headerQ = ", headerQ, "content = ", content);
}
if (question.id == 1) {
document.getElementById("headerQ").innerHTML = question[1].headerQ;
document.getElementById("content").innerHTML = question[1].content;
console.log("pullQuestions() Executed");
console.log("Variables: ", "headerQ = ", headerQ, "content = ", content);
}
if (question.id == 2) {
document.getElementById("headerQ").innerHTML = question[2].headerQ;
document.getElementById("content").innerHTML = question[2].content;
console.log("pullQuestions() Executed");
console.log("Variables: ", "headerQ = ", headerQ, "content = ", content);
}
}
I feel like I'm missing something small, but being that I'm new it's possible I'm approaching this all wrong. Any advice or direction is appreciated.
It doesn't work for you in the submitA button because you forgot to activate the call to in it pullQuestions
On the other hand, in startGame you did activate pullQuestions after you changed the id, so it works for you
This is what the function should look like
function submitA() {
question.id++;
pullQuestions();
console.log("submitA() Run)", "Question ID: ", question.id, headerQ, content);
}
I was able to get this to work. I added a variable to determine that the selection is "true." I also added a button to move to the next question so that the submit button / function is separate.
<script>
var sum = 0;
var pressYet = false;
function changeIt() {
if(pressYet == false){
sum++;
document.getElementById('test').innerHTML = sum;
pressYet = true;
} else {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
}
</script>
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()" id = "button" >Press If you are here</button>
SO I have this sweet epic button on my website, its very cool, but I want to make it better. I was wondering how to make the variable 'sum' not reset every time I refresh my website. I know there's a term for that but for the life of me I cannot figure it out. I want it so every time someone presses the button, 'sum' gets added one to it and that number would be permanent. So over time that number gets very large.
I am very new to HTML so please be kind to me.
You can save the value to localStorage and then retrieve it from localStorage after page load. Then on the basis of the data you can adjust the page. I have slightly modified your code here
var sum = 0;
var pressYet = localStorage.getItem('pressYet');
function changeIt() {
if (pressYet == null) {
sum++;
document.getElementById('test').innerHTML = sum;
pressYet = true;
localStorage.setItem('pressYet', pressYet);
} else {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
}
(function init() {
if (localStorage.getItem('pressYet') != null || localStorage.getItem('pressYet') != "") {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
})();
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()" id="button">Press If you are here</button>
You can check out the demo https://jsfiddle.net/5jyrk6s8/
I am making a quiz app that will basically fetch the questions and answers from an API and display it to the webpage. It works fine, but the error handling isn't working. I have a if...else statement that will check if a user has selected the right answer, and if they did, play a sound and display "Nice job" to the user. If they did not, then tell the user that they need to try again. The behavior that I'm getting is very weird. Sometimes when I have chose the correct answer, it says it is not correct. It happens when there is spaces within the answer. For single words such as "true", "false" or "Hello" works fine. I logged the answer to the console stored in a variable called answer_container, when I logged it to the console, the answer and my choice are exactly the same. I have tried using === and == operators to see if that would work, but the result is the same. I have posted the full code including my HTML so that you can see what it is happening. Note it took me couple of tries to get the weird behavior to display.
Here is what I have tried:
var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
document.getElementById('next').disabled = true;
document.getElementById('msgSuccess').innerHTML = '';
document.getElementById('check').disabled = false;
document.getElementById('showAnswer').disabled = false;
var getData = await fetch(url);
var toJS = await getData.json();
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i++) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
html_container = [];
container.forEach(function(choices) {
html_container.push(`
<option value=${choices}>
${choices}
</option>
`)
});
document.getElementById('choice').innerHTML = html_container.join();
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
} else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
}
fetchData();
showAnswer.addEventListener('click', function() {
document.getElementById('answer_element').innerHTML = "The answer to this question is " + answer_container;
document.getElementById('answer_element').style.display = "block";
setTimeout(function() {
document.getElementById('answer_element').style.display = "none";
}, 3000);
});
function check() {
var select_answer = document.getElementById('choice').value;
var audio = document.getElementById('audio');
if (select_answer == answer_container) {
score++;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
}
if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
}
}
<!DOCTYPE html>
<html>
<head>
<title>
Quiz App
</title>
</head>
<body>
<div id="type">
</div>
<label>
Select Your Answer...
</label>
<select id="choice">
</select>
<button id="showAnswer">
Show Answer
</button>
<p id="answer_element">
</p>
<button onclick="check()" id="check">
Check
</button>
<p id="msgSuccess">
</p>
<button id="next" onclick="fetchData()">
Next Question
</button>
<audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>
</html>
You're using the expression select_answer == answer_container to determine if the choice is the correct answer.
select_answer comes from the value attribute of the option you've selected. However, when an answer value contains whitespace, HTML interprets only up to the first whitespace as the "value". When answers like North America come up, the option's value attribute is only North.
When generating your options in your HTML, you need to properly encapsulate them in double quotes ", like so:
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
Tangential, but it would probably be cleaner if you generated your elements with document.createElement() and Node.appendChild(); in this instance the quotes required to properly set the value attribute on each option would have been added for you.
Nice game!
The issue here is the text is getting truncated on whitespace in the HTML, so the value you're comparing it too doesn't match.
You need quotes in the HTML option to preserve white space.
<option value=${choices} <- picks the first word
<option value="${choices}" <- allows the whole string with spaces
var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
document.getElementById('next').disabled = true;
document.getElementById('msgSuccess').innerHTML = '';
document.getElementById('check').disabled = false;
document.getElementById('showAnswer').disabled = false;
var getData = await fetch(url);
var toJS = await getData.json();
console.log(toJS)
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i++) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
html_container = [];
container.forEach(function (choices) {
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
});
document.getElementById('choice').innerHTML = html_container.join();
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
}
fetchData();
showAnswer.addEventListener('click', function () {
document.getElementById('answer_element').innerHTML = "The answer to this question is " + answer_container;
document.getElementById('answer_element').style.display = "block";
setTimeout(function () {
document.getElementById('answer_element').style.display = "none";
}, 3000);
});
function check() {
var select_answer = document.getElementById('choice').value;
var audio = document.getElementById('audio');
console.log(select_answer, answer_container)
if (select_answer == answer_container) {
score++;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
}
if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
}
}
<!DOCTYPE html>
<html>
<head>
<title>
Quiz App
</title>
</head>
<body>
<div id="type">
</div>
<label>
Select Your Answer...
</label>
<select id="choice">
</select>
<button id="showAnswer">
Show Answer
</button>
<p id="answer_element">
</p>
<button onclick="check()" id="check">
Check
</button>
<p id="msgSuccess">
</p>
<button id="next" onclick="fetchData()">
Next Question
</button>
<audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>
</html>
Ok so I'm kind of new in HTML/javascript, but I'm working on a project, which is a text-based game, basically, I want to have a function, which takes an array of text, print the first one in a text zone, and wait until the "ok" button in pressed before printing the next string of the array.this function is in the middle of a bunch of other ones.
Here is my code at the moment:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Retro-Fighting</title>
</head>
<body>
<br><br><br>
<input id="hpPlayer" type="text" value="" size="40" readonly>
<input id="hpBoss" type="text" value="" size="40" readonly>
<div id="sound_element"></div>
<script>
var player={
//Bunch of characteristics
};
var boss={
//Bunch of characteristics
};
var playerTurn=function()
{
var action =prompt("Do you want to : ATTACK , use MAGIC , or drink a POTION?").toLowerCase();
switch(action)
{
case 'attack':
var rand=10+(player.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(player.attack+rand-(boss.defense/2));
alert("You hit "+boss.name+" and deal "+damage+" damage points!" );
boss.hp-=damage;
if(boss.hp<0){boss.hp=0;}
showHp()
break;
case 'magic':
var rand=10+(player.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(player.attackM+rand-(boss.defenseM/2));
alert("You use "+player.magicName1+" on "+boss.name+" and deal "+damage+" damage points!" );
boss.hp-=damage;
if(boss.hp<0){boss.hp=0;}
showHp()
break;
case 'potion':
if(player.potion)
{
var heal = player.luck-Math.floor(Math.random()*20+1);
alert("You drink a potion and restore "+heal+" HP");
player.potion--
player.hp+=heal;
if(player.hp>player.hpMax){player.hp=player.hpMax;}
}
else {
alert("You don't have any potions left!")
playerTurn();
}
showHp()
break;
default:
confirm("You can't do that!");
playerTurn();
}
};
var bossTurn=function()
{
if(Math.floor(Math.random()+0.5))
{
var rand=10+(boss.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(boss.attackM+rand-(player.defenseM/2));
alert(boss.name+" use "+boss.magicName+" and deal "+damage+" damage points!" );
player.hp-=damage;
if(player.hp<0){player.hp=0;}
}
else
{
var rand=10+(boss.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(boss.attack+rand-(player.defense/2));
alert(boss.name+" hit you and deal "+damage+" damage points!" );
player.hp-=damage;
if(player.hp<0){player.hp=0;}
}
showHp()
};
var startBattle=function()
{
showHp()
while(player.hp>0&&boss.hp>0)
{
if(player.speed>boss.speed)
{
playerTurn();
if(boss.hp)
{bossTurn();}
}
else
{
bossTurn();
if(player.hp)
playerTurn();
}
}
if(player.hp)
{
alert("You won!")
//play victory sound
soundPlay("victory.mp3")
//Go to loot !
alert("Thank you for playing the demo of Retro-fighting!")
}
else
{
alert("You lost...The woodman is now free to destroy the world...")
soundPlay("gameover.mp3")
}
};
var showHp=function()
{
var outputHpPlayer = document.getElementById('hpPlayer')
var outputHpBoss = document.getElementById('hpBoss')
var stringHpPlayer= " "+ player.fName + ": " +player.hp+"/"+player.hpMax+" HP"
outputHpPlayer.value=stringHpPlayer
var stringHpBoss= " "+ boss.name + ": " +boss.hp+"/"+boss.hpMax+" HP"
outputHpBoss.value=stringHpBoss
}
var soundPlay=function(music)
{
document.getElementById("sound_element").innerHTML=
"<embed src="+music+" hidden=true autostart=true loop=false>";
}
confirm("You wake up...");
alert("You're wearing strange green clothes, and a sword is laying down, next to you...");
alert("You pick up the sword...An inscription on the blade say : Link" );
alert("You notice that you are in a dark corridor, a strange woodman is looking at you");
alert("The woodman is attacking you!");
startBattle();
</script>
</body>
</html>
Basically, I just want to get rid of the pop-up showing with the alert() command, while still waiting for a confirmation before showing more text
Since I'm really a beginner in programmation, tell me if my method isn't the right one ect...
Thank you!
PS: English is not my native language, sorry
Is this how your code is originally?
getBoss(//depending on the position o the player)
If so, then there is an error. The comment is extending all the way to the closing parenthesis.
I would like to ask somebody how i can determine what key was pressed in a textarea....
need to write a little javascript code.. a user type in a textarea and i need to write it in a while he writing so the keydown, keypress event handle this functionality, also need to change the text color if a user typed a "watched" word (or the word what he wrote contains the "watched" word/words ) in the textarea.. any idea how i can handle it ??
till now did the text is appear in the <div>, but with this i have a problem.. can't check if the text is in the "watched"... the document.getElementById('IDOFTHETEXTAREATAG'); on keypress is not really works because i got back the whole text inside of the textarea.....
So how i can do it ? any ideas ??? "(Pref. in Mozilla FireFox)
Well, if you were using jQuery, you could do this given that the id of your textarea was 'ta':
$('#ta').keypress(function (evt) {
var $myTextArea = $(this); // encapsulates the textarea in the jQuery object
var fullText = $myTextArea.val(); // here is the full text of the textarea
if (/* do your matching on the full text here */) {
$myTextArea.css('color', 'red'); // changes the textarea font color to red
}
};
I suggest you use the 'onkeyup' event.
$( element ).keyup( function( evt ) {
var keyPressed = evt.keyCode;
//...
});
I have this made like this (plain JS, no JQuery):
function keyDown(e) {
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
if (window.event.srcElement.tagName != 'TEXTAREA') {
var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
}
}
}
document.onkeydown=keyDown;
This script is in head tag. I am catching this in all textarea tags. Modify it for your purpose.
2 textareas.
In the first textarea I need to write the words or chars what you want to "watch" in the typing text.
In the second textarea I need to type text, so when I type text, under the textarea need to write what is in the textarea (real time) and highlight the whole word if contains the watched words or chars.
For example:
watched: text locker p
text: lockerroom (need to highlite the whole word because it contains the locker word) or apple (contains the p)
who I can do if a word not start with watched word/char to highlite the whole word?
JavaScript:
var text;
var value;
var myArray;
var found = new Boolean(false);
function getWatchedWords()
{
myArray = new Array();
text = document.getElementById('watched');
value = text.value;
myArray = value.split(" ");
for (var i = 0;i < myArray.length; i++)
{
document.getElementById('writewatched').innerHTML += myArray[i] + "<newline>";
}
}
function checkTypeing()
{
var text2 = document.getElementById('typeing');
var value2 = text2.value;
var last = new Array();
last = value2.split(" ");
if (last[last.length-1] == "")
{
if(found)
{
document.getElementById('writetyped').innerHTML += "</span>";
document.getElementById('writetyped').innerHTML += " ";
}
else
document.getElementById('writetyped').innerHTML += " ";
}
else
check(last[last.length-1]);
}
function check(string)
{
for (var i = 0; i < myArray.length; i++)
{
var occur = string.match(myArray[i]);
if(occur != null && occur.length > 0)
{
if (!found)
{
found = true;
document.getElementById('writetyped').innerHTML += "<span style='color: blue;'>";
}
else
{
found = true;
}
}
else
{
}
}
if(found)
{
document.getElementById('writetyped').innerHTML += string;
}
else
{
document.getElementById('writetyped').innerHTML += string;
}
}
HTML:
<html>
<head>
<title>TextEditor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<div>
<p>Watched words:</p>
<textarea id="watched" onblur=getWatchedWords();>
</textarea>
</div>
<div id="writewatched">
</div>
<div>
<p>Text:</p>
<textarea id="typeing" onkeyup=checkTypeing();>
</textarea>
</div>
<div id="writetyped">
</div>
</body>
</html>