Below is the html for an index page I've been working on. I want to create a button with an onclick function to say "hello world". So I used the script at the bottom of the page, but the button triggers the error described.
The most confusing part of it all, the button was functioning just fine until I changed the name of the function. I've had trouble since, even when I changed the name of the function back to what it is now.
<body>
<h1>Play Color Trivia</h1>
<div id="message">
</div>
<button onclick="sayhello()">speak</button>
<button id="roll_button" onclick="color_roll()">Color Roll</button><br><br>
<div id="color_box">
<div id="score_box">
<ul id="list" style="list-style-type: none">
<%= erb :token %>
</ul>
</div>
</div><br><br>
<div id="button_box">
<form id="color_form" method="post" target="frame">
</form>
</div><br><br>
<div id="question_box">
</div>
<div id="results">
</div>
<script src="/script.js" type="text/javascript">
</script>
<script src="http://code.responsivevoice.org/responsivevoice.js">
function sayhello(){
responsiveVoice.speak("hello world");
}
</script>
<iframe id="frame" name="frame"></iframe>
Script.js file
var evaluate; var list; var bullet; var colorize; var count; var stop; var change; var box; var roll_button; var button; var button_2; var message; var text; var question; var button_box = document.getElementById("button_box");
function color_roll(){
roll_button = document.getElementById("roll_button")
roll_button.style.display = "none"
box = document.getElementById("color_box");
change = setInterval(color,250)
stop = (Math.floor(Math.random() * 18))+1
// stop = 7
count = 0
}
function color(){
var array = ["red","orange","yellow","green","blue","purple","red","orange","yellow","green","blue","purple","red","orange","yellow","green","blue","purple"]
box.style.backgroundColor = array[count];
count += 1;
if (count == stop){
colorize = array[count-1]
clearInterval(change);
create_buttons();
color_selection();
}
}
function color_selection(){
if (colorize == "orange"){
message = document.getElementById("message");
text = document.createTextNode("You rolled an " + colorize);
message.appendChild(text);
rolled_color();
}
else{
message = document.getElementById("message");
text = document.createTextNode("You rolled a " + colorize);
message.appendChild(text);
rolled_color();
}
}
function helper(){
remove();
color_roll();
}
function create_buttons(){
button = document.createElement("input");
button_2 = document.createElement("input");
button.type = "button";
button_2.type = "button";
button.value = "Choose Color";
button_2.value = "Roll Again";
button.setAttribute("onClick","display()")
button_2.setAttribute("onClick","helper()");
button_box = document.getElementById("button_box");
button_box.appendChild(button);
button_box.appendChild(button_2);
}
function remove(){
button_box = document.getElementById("button_box");
button_box.removeChild(button);
button_box.removeChild(button_2);
message.removeChild(text);
}
//Create JSON objects for trivia questions
// var object = JSON.parse('{"red":"Three trivia questions will appear here"}')
function display(){
remove();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("question_box").innerHTML = this.responseText;
}
};
xhttp.open('GET','/question',true);
xhttp.send();
document.getElementById("question_box").style.display = "block"
}
function hello(){
console.log("hello world")
}
function display_result(){
// remove();
document.getElementById("submit").style.display = "none"
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML = this.responseText;
}
};
xhttp.open('GET','/test',true);
xhttp.send();
}
function rolled_color(){
var input = document.createElement("input");
input.style.display = "none";
var submit = document.createElement("input");
submit.style.display = "none";
input.name = "rolled_color";
input.value = colorize;
submit.type = "submit";
var form = document.getElementById("color_form")
form.appendChild(input)
form.appendChild(submit)
document.forms['color_form'].submit();
// display();
}
function add_bullet(){
document.getElementById("test").style.display = "none"
document.getElementById("evaluate_button").style.display = "none"
document.getElementById("question_box").style.display = "none"
evaluate = document.getElementById("value_input").value
bullet = document.createElement("li")
canvas = document.createElement("canvas")
var ctx = canvas.getContext("2d")
list = document.getElementById("list")
// list.style.list-style-type: none
canvas.width = 50
canvas.height = 50
// canvas.style.border = "2px solid black"
canvas.style.backgroundColor = colorize
// canvas.appendChild(document.createTextNode("test"))
if (evaluate == "You're Correct!"){
bullet.appendChild(canvas);
list.appendChild(bullet);
}
color_roll();
}
As described in this question
If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).
You need to use multiple script elements.
a <script> to load the external script
a <script> to hold your inline code (with the call to the function in the external script)
In your case you have to use two scripts as follows,
<script src="http://code.responsivevoice.org/responsivevoice.js">
</script>
<script>
function sayhello(){
//function calls to externel js
}
</script>
If an external script is referenced, the script inside is not executed
Related
Can someone explain to me or figure it out. I dont know where I made a mistake here. I have javascript and html code where I get input from user for a flight. I want to make a counter to count all flights function counter() but it gives me the value of name. And another problem is I want when I click on the Accept button to make the background of the div element green function changeColor().
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
var btn1 = document.createElement("BUTTON");
var btn2 = document.createElement("BUTTON");
var t1 = document.createTextNode("Accept");
var t2 = document.createTextNode("Reject");
btn1.appendChild(t1);
btn2.appendChild(t2);
divForOutput.innerHTML += name.value +", " + plainNum.value +"<br>" + "Radius: " + radius.value +", "+"Altitude: "+altitude.value+"<br>"+type.value+"<br>";
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
btn1.setAttribute('onclick','changeColor(this);');
btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
var parentofChild = document.getElementById("output");
output.div.background = green;
}
function counter(){;
var sum = document.getElementsByClassName("printing");
var counter = 0;
for(var i = 0;i <sum.length;i++){
counter+=parseInt(sum[i].innerHTML);
}
document.getElementById("total").innerHTML = counter;
}
<h1>Register flight</h1>
<form>
<div>
<label>Name and surname</label>
<input type="text" id="name">
</div>
<div>
<label>Number plate</label>
<input type="text" id="plainNum">
</div>
<div>
<label>Coordinates</label>
<input type="text" id="coordinates">
</div>
<div>
<label>Radius</label>
<input type="text" id="radius">
</div>
<div>
<label>Altitude</label>
<input type="text" id="altitude">
</div>
<div>
<label>Type</label>
<select id="type">
<option value="Comercial">Comercial</option>
<option value="Buissines">Buissines</option>
</select>
</div>
<div>
<input type="button" value="Submit" onclick="addRow();">
</div>
</form>
<divи>
<h3>Registered flights</h3>
<p>Total:<span id="total">0</span></p>
</div>
<div id="output">
</div>
Below I've fixed some of the code and made things a bit better.
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
//var btn1 = document.createElement("BUTTON");
//var btn2 = document.createElement("BUTTON");
//var t1 = document.createTextNode("Accept");
//var t2 = document.createTextNode("Reject");
//btn1.appendChild(t1);
//btn2.appendChild(t2);
divForOutput.innerHTML = `
${name.value}<br>
Radius: ${radius.value}<br>
Altitude: ${altitude.value}<br>
${type.value}<br>
<button onclick="changeColor();">Accept</button>
<button onclick="disableButtons();">Reject</button>
`;
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
//btn1.setAttribute('onclick','changeColor(this);');
//btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
const output = document.getElementById("output");
output.style.backgroundColor = "green";
}
function counter(){;
const sum = document.getElementsByClassName("printing");
const counter = sum.getElementsByTagName('div').length;
return document.getElementById("total").innerHTML = counter;
}
There is an explanation for the background color here
As for the counter; what I did was count the div elements inside of the output div. That will give you the amount of flights a user has.
Your color setting had several problems. You don't use output.div.background to set the color, and you were using the undefined variable green instead of the string "green". This works:
function changeColor(){
var output = document.getElementById("output");
output.style.backgroundColor = 'green';
}
I don't know what you are trying to count with your counter function, so I can't fix that.
i am creating a todo list as a beginner exercise to train my JS skills but i hit a wall (again). As you can see in my code, i can create tasks that need doing and to each task i appended 2 buttons. Now i want both buttons to do the same thing (remove the task). I would like to create a addEventListener to those buttons but since i created them through JS and not HTML i don't now how to access them or their behavior (i don't know how to get their ID or if they even have one). So my question is this: how can i access those buttons through JavaScript? Thanks.
let b1 = document.getElementById('addItem');
let d1 = document.getElementById('resetList');
let content = document.getElementById('listItem').value;
let Liste = document.getElementById('laListe');
var addTask = function() {
var text = document.getElementById('listItem').value;
var li = document.createElement('li');
var buttons = document.createElement('button');
buttons.innerHTML = "X";
var buttons2 = document.createElement('button');
buttons2.innerHTML = "Done";
li.innerHTML = text;
li.append(document.createTextNode(" "));
document.getElementById('laListe').appendChild(li).appendChild(buttons);
li.append(document.createTextNode(" "));
li.append(buttons2);
}
document.getElementById('addItem').onclick = function(event) {
event.preventDefault()
};
b1.addEventListener('click', function() {
addTask();
});
d1.addEventListener('click', function() {
document.getElementById('laListe').innerText = " ";
});
document.getElementById('resetList').onclick = function(event) {
event.preventDefault()
};
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="Todo.css">
<title>ToDo App</title>
<script src='todo.js' defer></script>
</head>
<body>
<h1>To-Do List</h1>
<form id="Listcreator" name="itemAdd">
<input id="listItem" type="text">
<button id="addItem" type="submit"> Ajouter </button>
<button id="resetList" type="submit"> Tout Enlever</button>
</form>
<ul id="laListe"> </ul>
</body>
var buttons = document.createElement('button');
buttons.innerHTML = "X";
buttons.addEventListener("click", function(){
this.parentNode.remove();
});
var buttons2 = document.createElement('button');
buttons2.innerHTML = "Done";
buttons2.addEventListener("click", function(){
this.parentNode.remove();
});
You can add an event listener to your buttons when they are created.
https://jsfiddle.net/cnsxaL3b/
After adding event listeners, your code should look like below:
let b1 = document.getElementById('addItem');
let d1 = document.getElementById('resetList');
let content = document.getElementById('listItem').value;
let Liste = document.getElementById('laListe');
var addTask = function() {
var text = document.getElementById('listItem').value;
var li = document.createElement('li');
var buttons = document.createElement('button');
buttons.innerHTML = "X";
var buttons2 = document.createElement('button');
// Event listener for first button
buttons.addEventListener('click', function() {
alert('clicked button1');
});
// Event listener for first button
buttons2.addEventListener('click', function() {
alert('clicked button2');
});
buttons2.innerHTML = "Done";
li.innerHTML = text;
li.append(document.createTextNode(" "));
document.getElementById('laListe').appendChild(li).appendChild(buttons);
li.append(document.createTextNode(" "));
li.append(buttons2);
}
document.getElementById('addItem').onclick = function(event) {
event.preventDefault()
};
b1.addEventListener('click', function() {
addTask();
});
d1.addEventListener('click', function() {
document.getElementById('laListe').innerText = " ";
});
document.getElementById('resetList').onclick = function(event) {
event.preventDefault()
};
I'm having trouble working with my next button on my webpage. I can get the other parts of the page (the answer message) to show up fine with when the button is clicked, but for some reason it will not work with this next button. Hiding it works fine, but when I click the button the next button will not show up. If I don't hide or style = "none", the button shows up fine. I've tried .style = "none" & .style = "block" and .visibility = "hidden" and .visibility = "visible", with no success. If anyone could give me some insight I'd appreciate it!
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky() {
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
} else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next() {
};
<div class="user-response">
What is <input type="text" id="user_answer"> ?
<button onclick="clicky()" type=b utton>Submit</button>
<button onclick="next()" type=s ubmit id="next">Next -></button>
</div>
<p id="correct">{{clue.answer}}</p>
<p id="score">{{score}}</p>
<p id="value">{{clue.worth}}</p>
<form method="GET">
<input type="hidden" name="score_get" value=0>
</form>
<div class="answer" id="answer">
</div>
At the end of the clicky function you are trying to set the innerHTML of a missing element "showed_score", It results with an error and quit the function before it is done.
Just remove this line or add the element to your html
I created this interactive snippet. Looks like there is an error (Uncaught TypeError: Cannot read property 'innerHTML' of null) happening right above that is throwing console errors. Based on your code the elements showed_score and score_get do not exist. Fixing this will hopefully fix your original problem.
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id = "next">Next -></button>
</div>
<p id = "correct"></p>
<p id = "score"></p>
<p id = "value"></p>
<form method = "GET">
<input type = "hidden" name = "score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>
<script type = "text/javascript">
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next(){
};
</script>
I don't know what template engine youre using to render {{clue.answer}} but I imagine there's an answer in there somewhere. Try the following code instead (you were missing an id reference for getElementById :
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id = "next">Next -></button>
</div>
<p id = "correct">{{clue.answer}}</p>
<p id = "score">{{score}}</p>
<p id = "value">{{clue.worth}}</p>
<form method = "GET">
<input type = "hidden" name = "score_get" id="score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>
<div id="showed_score">
</div>
<script type = "text/javascript">
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + Math.floor(score);
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
}
function next(){
}
</script>
Try commenting these 2 lines:
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
They trigger an error which prevents the button from becoming visible.
You probably have an error before it gets to the code for visibility.
Look in your console to find errors and what is causing it.
Here's your example with most of it commented out and it works:
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
//var correct = document.getElementById("correct").innerHTML;
//var score = document.getElementById("score").innerHTML;
//var value = document.getElementById("value").innerHTML;
//var val2 = value.substring(1);
//var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
//document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
//score -= worth;
}
//document.getElementById("showed_score").innerHTML = "Score is now $" + score;
//document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next(){
};
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id="next">Next -></button>
</div>
<p id = "correct">{{clue.answer}}</p>
<p id = "score">{{score}}</p>
<p id = "value">{{clue.worth}}</p>
<form method = "GET">
<input type = "hidden" name = "score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>
I want to make a webpage with 2 buttons (Add, Delete). Conditions are using div id divResult , console log and after removing that div has to stay. It works almost correct, just last step (remove alinea) doesn`t work. Can you help me , how can i fix it? :-)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>2 buttons</title>
<script >
var index = 1;
window.onload = function () {
document.getElementById('Btn1').onclick = function () {
var newElement = document.createElement('div');
newElement.id = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
};
document.getElementById('Btn2').onclick = function () {
var oldDiv = document.getElementById('txtElement')
var alinea = oldDiv.querySelectorAll('p:last-child')[0];
console.log(alinea + ' wordt verwijderd...');
oldDiv.removeChild(alinea);
console.log('verwijderd!');
};
};
</script>
</head>
<body>
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
</body>
</html>
I've tried a few things, moved stuff around. I think it's doing what you want now.
var index = 1;
window.onload = function () {
document.getElementById('Btn1').onclick = function () {
var newElement = document.createElement('div');
newElement.id = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
};
document.getElementById('Btn2').onclick = function () {
var oldDiv = document.getElementById('txtElement');
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('div:last-child')[0];
console.log(alinea + ' wordt verwijderd...');
alinea.remove();
// divResult.removeChild(alinea);
console.log('verwijderd!');
};
};
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
If I understand you correctly, change the following section:
document.getElementById('Btn2').onclick = function () {
var alinea = document.getElementById('div'+ --index);
console.log(alinea.innerHTML + ' wordt verwijderd...');
alinea.remove(alinea);
console.log('verwijderd!');
};
I need some help to get my program running. Its been a week and I have only made such little progress with youtube videos and google search.
I want to design a simple web application like the on on this website http://text2data.org/Demo.
With some help i was able to find the following javascript from http://www.the-art-of-web.com/javascript/search-highlight/#withutf8 that i could modify.
I have developed how i want my interface to look like but i am stuck at achieving the primary objective of keyword highlighting.
I have therefore turned to the only community i know best to help me get through this so as to make the dead line by Monday.
MODIFIED JAVA CODE ADOPTED FROM CHIRP
// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function Hilitor(id, tag)
{
var targetNode = document.getElementById(id) || document.getElementById(SentenceIn);
var hiliteTag = tag || "EM";
var skipTags = new RegExp("^(?:" + hiliteTag + "|SCRIPT|FORM|SPAN)$");
var colors = ["#ff6", "#a0ffff", "#9f9", "#f99", "#f6f"];
var wordColor = [];
var colorIdx = 0;
var matchRegex = "";
var openLeft = false;
var openRight = false;
this.setMatchType = function(type)
{
switch(type)
{
case "left":
this.openLeft = false;
this.openRight = true;
break;
case "right":
this.openLeft = true;
this.openRight = false;
break;
case "open":
this.openLeft = this.openRight = true;
break;
default:
this.openLeft = this.openRight = false;
}
};
this.setRegex = function(input)
{
input = input.replace(/^[^\w]+|[^\w]+$/g, "").replace(/[^\w'-]+/g, "|");
var re = "(" + input + ")";
if(!this.openLeft) re = "\\b" + re;
if(!this.openRight) re = re + "\\b";
matchRegex = new RegExp(re, "i");
};
this.getRegex = function()
{
var retval = matchRegex.toString();
retval = retval.replace(/(^\/(\\b)?|\(|\)|(\\b)?\/i$)/g, "");
retval = retval.replace(/\|/g, " ");
return retval;
};
// recursively apply word highlighting
this.hiliteWords = function(node)
{
if(node === undefined || !node) return;
if(!matchRegex) return;
if(skipTags.test(node.nodeName)) return;
if(node.hasChildNodes()) {
for(var i=0; i < node.childNodes.length; i++)
this.hiliteWords(node.childNodes[i]);
}
if(node.nodeType == 3) { // NODE_TEXT
if((nv = node.nodeValue) && (regs = matchRegex.exec(nv))) {
if(!wordColor[regs[0].toLowerCase()]) {
wordColor[regs[0].toLowerCase()] = colors[colorIdx++ % colors.length];
}
var match = document.createElement(hiliteTag);
match.appendChild(document.createTextNode(regs[0]));
match.style.backgroundColor = wordColor[regs[0].toLowerCase()];
match.style.fontStyle = "inherit";
match.style.color = "#000";
var after = node.splitText(regs.index);
after.nodeValue = after.nodeValue.substring(regs[0].length);
node.parentNode.insertBefore(match, after);
}
};
};
// remove highlighting
this.remove = function()
{
var arr = document.getElementsByTagName(hiliteTag);
while(arr.length && (el = arr[0])) {
var parent = el.parentNode;
parent.replaceChild(el.firstChild, el);
parent.normalize();
}
};
// start highlighting at target node
this.apply = function(input)
{
this.remove();
if(input === undefined || !input) return;
this.setRegex(input);
this.hiliteWords(targetNode);
};
}
MY HTML PAGE
#model DataAnalyzer.Models.EnterSentence
#{
ViewBag.Title = "Data Analysis";
}
#section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
</hgroup>
</div>
</section>
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Enter Sentence</title>
<script type="text/javascript" src="~/Scripts/hilitor.js"></script>
<script type="text/javascript">
function dohighlight() {
var myHilitor = new Hilitor("SentenceIn");
myHilitor.apply("badWords");
//Variable for output text
var enteredText = document.getElementById("SentenceIn").value;
//Hide analyze button
document.getElementById("highlight").style.display = 'none';
//show result text area
document.getElementById("result").style.display = 'block';
//display text in results text area
document.getElementById("result").innerHTML = myHilitor;
}
</script>
</head>
<body>
<div>
<p>
Welcome to Data Analysis, Please enter a sentence in the textbox below.
</p>
#using (Html.BeginForm())
{
<div id="sentenceOut" style=" height:auto; width:500px">
#Html.TextArea("SentenceIn")
</div>
<input id="highlight" type="button" value="Analyze" onclick="dohighlight();" /> <br />
<div id="result" style="display:none; background-color:#ffffff; float:left; min-height:200px; width:500px;">
I am some text from the box up there
</div>
<div id="goodWords" style=" background-color:#ffffff; min-height:200px; width:500px;">
Good excelent bravo awesome splendid magnificent sweet estatic plaudible love like
</div>
<div id="neutralWords" style=" background-color:#ffffff; min-height:200px; width:500px;">
lukewarm maybe meh suppose
</div>
<div id="badWords" style=" background-color:#ffffff; min-height:200px; width:500px;">
fuck shit evil damn cock bullshit hate dislike poor
</div>
<script type="text/javascript">
document.getElementById("goodWords").style.visibility = 'hidden';
document.getElementById("neutralWords").style.visibility = 'hidden';
document.getElementById("badWords").style.visibility = 'hidden';
</script>
}
</div>
</body>
</html>