Highlight Text in Text Field at a Specific Point - javascript

I'm trying to replicate Twitter's "compose new tweet" box. I have a counter that shows how many letters you have left. I'm not using HTML's maxlength, so when you go into the negatives, the counter turns red and is negative. In Twitter, your overflowed text is highlighted a light red.
How would I manage to highlight overflowed text in a text field? Here's my HTML and JavaScript that I already have. (I've attempted to highlight the text before but I didn't know where to start 'cuz I'm a noob. :P ):
<div id="char_count">
<span id="charsLeftH" title="Characters Remaining" style="cursor: pointer">500</span>
</div>
<input type="button" value="Send" id="submit">
<script>
var chars = 500;
function charsLeft() {
chars = 500 - $("#type_area").val().length;
document.getElementById("charsLeftH").innerHTML=chars;
if (chars < 50 && chars > 0) {
document.getElementById("charsLeftH").style.color="#9A9A00";
document.getElementById("submitX").id="submit";
} else if (chars < 1) {
document.getElementById("charsLeftH").style.color="#BD2031";
if (chars < 0) {document.getElementById("submit").id="submitX";}
} else {
document.getElementById("charsLeftH").style.color="#000000";
document.getElementById("submitX").id="submit";
}
};
charsLeft();
</script>

here is the script
jfiddle:
style:
<style type="text/css">
.red{
color:#F00;
}
#mytextarea{
background-color:#999;
filter:alpha(opacity=50);
opacity:0.5;
border: 1px #3399FF solid;
min-height:50px;
width:150px;
word-wrap:break-word;
}
</style>
html:
<div contenteditable="true" id="mytextarea" onChange="charsLeft(this.innerHTML)" onKeyUp="charsLeft(this.innerHTML)"></div> <div id="remaining"></div>
javascript:
<script>
var before = 1;
var chars = 10;
var len = 0;
var div = document.getElementById('mytextarea');
var el = document.getElementById('remaining');
el.innerHTML = chars;
var overchars = 92; //length of the tags
function charsLeft(val) {
if (typeof (val) != 'undefined') {
val = val.replace('<font style="background-color:#F36;" id="reddragonred">', '');
val = val.replace('</font>', "");
len = val.length;
if (len > chars) {
plusvalor = val.slice(chars, len);
redstr = '<font style="background-color:#F36;" id="reddragonred">' + plusvalor + '</font>';
blackstr = val.slice(0, chars);
div.innerHTML = blackstr + redstr;
var subj = document.getElementById('reddragonred');
var cursorepos = subj.innerHTML.length;
var range = document.createRange();
var sel = window.getSelection();
console.log(before+' '+len);
if((before>0)&&(before<len)){
console.log('no');
try{
console.log(cursorepos);
if(cursorepos==0){
range.setStart(subj, 0);
}else{
range.setStart(subj, 1);
}
}catch (e){
console.log(e);
}
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
div.focus();
}
before=len;
}
}
el.innerHTML = chars - len;
}
</script>

Related

Caret tracking in a ContentEditable or a Textarea copied to. Account for child div, span, img, p, br HTML tags and more

I'm dabbling in jquery and javascript to get done what I need. At the heart of the problem is an emoji picker that I coded in PHP. It inserts emoji just fine, but it doesn't insert at the caret position. Every script I've found somehow fails to account for the html tags. The count is always wrong, so where the emoji is inserted can vary, sometimes in the middle of an html tag, which turns the editor box into a horrible hurricane-stricken site.
<script>
/* VERSION 2 8/21/2022 */
function getCharacterOffsetWithin_final(range, node) {
var treeWalker = document.createTreeWalker(
node,
NodeFilter.ELEMENT_NODE,
function(node) {
var nodeRange = document.createRange();
nodeRange.selectNodeContents(node);
return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ?
NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
},
false
);
var charCount = 0, lastNodeLength = 0;
if (range.startContainer.nodeType == 3) {
charCount += range.startOffset;
}
while (treeWalker.nextNode()) {
charCount += lastNodeLength;
lastNodeLength = 0;
if(range.startContainer != treeWalker.currentNode) {
if(treeWalker.currentNode instanceof Text) {
lastNodeLength += treeWalker.currentNode.length;
} else if(treeWalker.currentNode instanceof HTMLBRElement ||
treeWalker.currentNode instanceof HTMLImageElement ||
treeWalker.currentNode instanceof HTMLSpanElement ||
treeWalker.currentNode instanceof HTMLDivElement)
{
lastNodeLength++;
}
}
}
return charCount + lastNodeLength;
}
var update = function() {
var el = document.getElementById("interim");
var range = window.getSelection().getRangeAt(0);
$(\'#cursorPos\').text(getCharacterOffsetWithin_final(range, el));
};
$("#commentsbox").on("mouseup keyup", update);
/* VERSION 2 END 8/21/2022 */
var interim = function() {
$(\'#interim\').val($(this).text());
};
$(\'#commentsbox\').on("mousedown mouseup keydown keyup", interim);
<div class="input" role="textbox" contentEditable="true" data-placeholder="Comment here..." name="comment-content" style="word-break: break-word;word-wrap: break-word;font-size:x-large;padding:5px;text-align:left;display:inline-block;min-height:100px;width:95%;border:solid 0.75px '.$bordercolor.';" id="commentsbox" class="'.$_SESSION['theme'].'"></div>
<div id="cursorPos"></div>
<textarea id="interim" style="display:none;"></textarea>
<div style="position:relative;display:inline-block;display:none;padding:5px;text-align:left;min-height:20px;min-width:95%;border-left:solid 0.75px '.$bordercolor.';border-right:solid 0.75px '.$bordercolor.';" id="menubox" class="hiddencontrols">
<span style="display:inline-block;height:100%;width:50px;" class="material-icons emojilist_tog"><img src="https://rellawings.com/emoji/blobdrool2.png" height="24px" \>arrow_drop_down</span><span class="material-icons" style="display:inline-block;padding-left:10px;padding-right:10px;">format_quote</span><span style="display:inline-block;"><img src="https://rellawings.com/images/spoiler.png" height="20px" /></span>
</div>
<div class="emojilist" style="display:none;width:300px;max-height:200px;position:absolute;z-index:1000000;text-align:center;">
<div style="display:inline-block;font-weight:bolder;font-size:large;text-align:center;background-color:#292929;width:280px;padding:10px;">Emoji</div>
<div style="position:relative;padding-left:8px;text-align:center;background-color:#1e1e1e;padding-top:12px;padding-bottom:12px;max-height:150px;overflow-x:hidden;overflow-y:scroll;">';
$emojifullpath = '/home/gwingdivineknight/rellawings.com/emoji/';
$emojidir = 'https://rellawings.com/emoji/';
$emojifiles = array_diff(scandir($emojifullpath), array('..', '.')); $i = 1;
foreach ($emojifiles as &$value) {
$cleanname = basename($value,".png");
$body .= '<span style="display:inline-block;padding:3px;"><img src="'.$emojidir.$value.'" height="24px" id="emoji-'.$i.'" /></span>';
$body .= '
<script>
$(document).ready(function(){
$("#emoji-'.$i.'").click(function(event){
var emoimg = "<span style=\'display:inline;padding:4px;position:relative;bottom:-4px;\'><img src=\'https://rellawings.com/emoji/'.$value.'\' title=\':'.$cleanname.':\' alt=\':'.$cleanname.':\' height=\'24px\' /></span>";
/* Proven To Work Except for Positioning */
/*$(\'#commentsbox\').append(emoimg);
var TotalContents = $(\'#commentsbox\'),
fix = TotalContents.html().replaceAll("<br>", "");
TotalContents.html(fix);*/
cursorPos = $(\'#cursorPos\').html();
var v = $(\'#commentsbox\').html();
var textBefore = v.substring(0, cursorPos );
var textAfter = v.substring( cursorPos, v.length );
$(\'#commentsbox\').html(textBefore+ emoimg +textAfter);
});
});
</script>
';
$i++;
}
$body .= '
</div>
</div>
<div style="display:inline-block;display:none;padding:5px;text-align:right;min-height:40px;min-width:95%;position:relative;border:solid 0.75px '.$bordercolor.';" id="buttonsbox" class="hiddencontrols">
<span style="display:inline-block;padding:5px;background-color:#292929;border-radius:7px;margin-right:4px;margin-bottom:6px;margin-top:6px;
white-space:nowrap;color:#ffffff;cursor: pointer;position:relative;width:67px;" id="cancelbtn"><span class="material-icons" style="position:absolute;left:2px;top:2px;">clear</span>Cancel</span>
<span style="display:inline-block;padding:5px;background-color:#292929;border-radius:7px;margin-right:4px;margin-bottom:6px;margin-top:6px;
white-space:nowrap;color:#ffffff;cursor: pointer;position:relative;width:53px;" id="postbtn"><span class="material-icons" style="position:absolute;left:2px;top:2px;">create</span>Post</span>
</div>
I'm at the end of my patience with attempting to get my emoji picker + contenteditable div work. The functions that I find don't return a perfect number of characters in tags and outside, so it's not able to place emoji accurately into the contenteditable div.
Thanks in advance for your help!
The answer was found! This lovely bit of code was contributed by a friend. Thanks to everyone for all the wonderful assistance! Here's the lovely solution! I'm sure it will help many people who get frustrated over the same sort of situation, looking for a simpler solution! <3
<script>
function pasteHtmlAtCaret(emojiHtml) {
let sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
const el = document.createElement("div");
el.innerHTML = emojiHtml;
let frag = document.createDocumentFragment(),
node,
lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(emojiHtml);
}
}
function addToCommentsBox(emojiHtml) {
const chatBox = document.getElementById("commentsbox");
chatBox.focus();
pasteHtmlAtCaret(emojiHtml);
}
</script>

Javascript for loop not repeating strings

very new to Javascript here, and I think I'm having a logic issue. So basically for class I'm building a hangman game, and I am having trouble with double letters. for instance if the word is food, when I enter an "O" it will pass through the for loop, hit that first O, push it to the screen, and stop dead in its tracks. I can do whatever I want to that first "O" but a second one or any other repeated letter gets ignored. Now the alert I wrote directly under the start of the for() loop, will successfully print both "O's", as will logging it to the console, or even flat out writing document.write(splitWord[m]);
So to me, I think it has to be my if statement. I could be 100% wrong on this, but I assume that the if statement tells it to see the first "O", do what's in the bracket, and then move on to the next letter skipping any doubles. If I am right about this, what would be a better option to keep the loop going, so both "O's" would be filled. And if I am completely wrong, what would be a better course of action to accomplish this task. Any help would be very greatly appreciated.
Thanks
var remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var removedLetters =[];
var wordList = ["django", "the#good#the#bad#and#the#ugly", "a#fistful#of#dollars","for#a#few#dollars#more","once#upon#a#time#in#the#west","the#wild#bunch","pale#rider"];
var titleList =["django", "The Good The Bad And The Ugly", "A Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"];
var songList =["Jango", "The Good The Bad And The Ugly", "Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"]
var selectedWord;
console.log(selectedWord);
var livesRemaining = 12;
var score = 0;
var wordWorth = 0;
var wins = 0;
var losses = 0;
var gameOn = false;
function chooseAWord(){
selectedWord = wordList[Math.floor(Math.random() * wordList.length)];
console.log(selectedWord);
}
function printWord(){
document.getElementById("wordDisplayer").innerHTML = selectedWord;
}
function buildTiles(){
// create a new div element
// and give it some content
var splitWord = selectedWord.split("");
for(i = 0; i < splitWord.length; i++){
if (splitWord[i] != '#'){
// var newTile = document.createElement("div");
//var newContent = document.createTextNode("");
//newTile.appendChild(newContent); //add the text node to the newly created div.
document.getElementById("wordTiles").innerHTML += '<div class="tileStyle" id="' + splitWord[i] + '"></div>';
wordWorth++;
// add the newly created element and its content into the DOM
//var currentDiv = document.getElementById("wordTiles");
//currentDiv.appendChild(newTile, currentDiv);
// newTile.setAttribute("class", "tileStyle");
}else if(splitWord[i] == '#'){
var blankTile = document.createElement("div");
var spaceContent = document.createTextNode("");
blankTile.appendChild(spaceContent);
document.getElementById("wordTiles").innerHTML += '<div class="blankStyle" id="' + splitWord[i] + '"></div>';
}
}
}
function clearTiles(){
var myNode = document.getElementById("wordTiles");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
function refreshAlphabet(){
remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
displayAvailableLetters();
}
function keyPressed(){
checkPlayerChoiceNew();
}
var playerGuess = document.onkeyup = function myKeyDown(event){
playerGuess = event.key;
if(gameOn==true){
keyPressed();
}else{
}
}
function checkPlayerGuess(){
document.getElementById("isThisWorking").innerHTML = playerGuess;
}
// function myFunction() {
// var str = "Tha bast things in lifa ara free";
// var patt = new RegExp(playerGuess);
// var res = patt.test(selectedWord.toLowerCase());
// document.getElementById("demo").innerHTML = res;
//}
function displayAvailableLetters(){
document.getElementById("lettersStillAvailable").innerHTML = remainingLetters;
console.log(remainingLetters);
}
function displayRemovedLetters(){
document.getElementById("lettersUsed").innerHTML = removedLetters;
}
function updateScore(){
document.getElementById("scoreTotal").innerHTML = score;
}
function updateWins(){
document.getElementById("winTotals").innerHTML = wins;
}
function updateLosses(){
document.getElementById("lossTotals").innerHTML = losses;
}
function checkScore(){
if(score == selectedWord.length && livesRemaining > 0){
document.getElementById("gameOver").innerHTML = "WINNER! Congratulations!!!";
wins++;
updateWins();
gameOn=false;
}else if (livesRemaining == 0){
livesRemaining == -1;
document.getElementById("gameOver").innerHTML = "You have failed!";
losses++;
updateLosses();
gameOn=false;
}else{
document.getElementById("gameOver").innerHTML = "Good Luck!";
}
}
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = playerGuess;
}
}
}
//check playerGuess against selectedWord
function checkPlayerChoice(){
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
if(compareWord == true && compareAlphabet == true ){
document.getElementById("demo").innerHTML = playerGuess;
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
displayAvailableLetters();
displayRemovedLetters();
score++;
updateScore();
checkScore();
}else if(compareWord == true && compareAlphabet == false){
document.getElementById("demo").innerHTML = "Already tried that one";
}else if(compareWord == false && compareAlphabet == true){
livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
document.getElementById("demo").innerHTML = "Already tried that one ;)";
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
}else{
/*livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();*/
document.getElementById("demo").innerHTML = "Not a Valid Key";
}
}
//document.onkeyup = function myKeyDown(event){
// playerGuess = event.key;
//}
//start / Restart the game
function resetGame() {
livesRemaining = 12;
score =0;
wordWorth = 0;
clearTiles();
document.getElementById("lives").innerHTML = livesRemaining;
chooseAWord();
printWord();
buildTiles();
refreshAlphabet();
gameOn=true;
}
.tileStyle{
width:30px;
height:30px;
border:1px solid black;
background-color:green;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.blankStyle{
width:30px;
height:30px;
background-color:orange;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.fixer{
width:100%;
height:10px;
clear:both;
}
<body>
<button onclick="checkPlayerChoice()">Try it</button>
<p id="demo"></p>
<p> lives: </p>
<p id = "lives"> 0</p>
<p> Score: </p>
<p id = "scoreTotal">0</p>
<p>wins</p>
<p id ="winTotals">0</p>
<p>losses</p>
<p id ="lossTotals">0</p>
<p id ="gameOver"></p>
<button onclick ="resetGame()">New Game</button>
<p>Here is the word</p>
<p id = "wordDisplayer">Press New Game to Start</p>
<div id = "wordTiles"></div>
<div class ="fixer"></div>
<button onclick ="checkPlayerGuess()">What Key was Pressed?</button>
<p id ="isThisWorking">What will I say?</p>
<p>Letters Still Available</p>
<p id ="lettersStillAvailable"></p>
<p>Bad Guesses</p>
<p id ="lettersUsed"></p>
<br />
selectedWord ="food";
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = choice;
}
}
}
You can refer this below logic. In this example, I have given some inputs.
var selectedWord ="food";
var displayString = [];
for(var i = 0; i < selectedWord.length; i++){
displayString[i] = "-"
}
var outputEle = document.getElementById("output");
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
function checkPlayerChoiceNew(playerGuess){
var newWord = "";
var regExp = new RegExp(playerGuess,'ig')
selectedWord.replace(regExp, function(value, index){
displayString[index] = value;
return value;
});
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
newWord = displayString.join("");
if(selectedWord == newWord){ alert("You Won the game"); }
//outputEle.innerText = displayString.join(" ");
}
checkPlayerChoiceNew('o');
checkPlayerChoiceNew('g');
checkPlayerChoiceNew('d');
checkPlayerChoiceNew('f');
<div id="output">
</div>

Highlight Keywords in a given text area based on list of words

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>

How to show markup color code in my phpbb BBCode

I have default [code] [/code] BBCode on my phpbb forum. But it does not show the color for code's markup. I want to see the exact color for every php, html, css color etc color.
I used bellows code there to create BBCode.
HTML Replacement :
<script type="text/javascript">
// select all function
function selectCode(a)
{
// Get ID of code block
var e = a.parentNode.parentNode.getElementsByTagName('CODE')[0];
// Not IE and IE9+
if (window.getSelection)
{
var s = window.getSelection();
// Safari
if (s.setBaseAndExtent)
{
s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
}
// Firefox and Opera
else
{
// workaround for bug # 42885
if (window.opera && e.innerHTML.substring(e.innerHTML.length - 4) == '<BR>')
{
e.innerHTML = e.innerHTML + ' ';
}
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
}
// Some older browsers
else if (document.getSelection)
{
var s = document.getSelection();
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
// IE
else if (document.selection)
{
var r = document.body.createTextRange();
r.moveToElementText(e);
r.select();
}
}
//expand - collapse settings
function expandcollapse(a) {
var ee = a.parentNode.parentNode.getElementsByTagName('dd')[0];
if (ee.style.maxHeight == '200px')
{
ee.style.maxHeight = '2000px';
a.innerHTML = 'collapse';
}
else {
ee.style.maxHeight = '200px';
a.innerHTML = 'expand';
};
}
</script>
<![if !IE]>
<script type="text/javascript">
function scrolltest(k) {
var eee = k.getElementsByTagName('dd')[0];
var old = eee.scrollTop;
eee.scrollTop += 1;
if (eee.scrollTop > old) {
eee.scrollTop -= 1;
k.getElementsByTagName('a')[1].style.visibility = "visible";
}
}
</script>
<![endif]>
<div class="pre" onmouseover="scrolltest(this); return false;">
<dt class="pre_header">
<b>Code: </b>
Select all
<a style="float:right; visibility:hidden;" href="#" onclick="expandcollapse(this); return false;">expand</a>
</dt>
<dd style="max-height:200px; overflow:auto;">
<code>
{TEXT}
</code>
</dd>
</div>
If you're looking for a syntax highlighter, check out this phpbb plugin/mod:
http://sourceforge.net/projects/geshi-phpbb/
Read GeSHi for more.

See if div contains one or more entered words (Javascript)

I would like to check if any div contains all words entered in an input field. However, currently I am stuck in a situation that as soon as a space is entered, it starts all over, and thus sort of acts like an OR operator instead of an AND operator. Could anyone please push me in the right direction? Thanks a lot!
This is what I have so far:
<div class="search">aa ab ac ad</div>
<div class="search">ab ba bb bc</div>
<div class="search">bb cc dd ee</div>
<script>
function search(query) {
var divs= document.getElementsByTagName('div');
var words = query.toLowerCase().split(" ");
for (var h = 0, len = divs.length; h < len; ++h) {
for (var i = 0; i < words.length; i++) {
if (divs[h].innerHTML.indexOf(words[i]) == -1) {
divs[h].style.backgroundColor = '#fff';
}
else {
divs[h].style.backgroundColor = '#ddd';
}
}
}
}
</script>
<input type="text" onkeyup="search(this.value);">
Apparently I was not very clear. My apologies.
What direction do I need to go to make it in Javascript so that it looks for if a div contains AND words[0] AND words[1] AND words[2], etc (so, in any random order)?
Right now when a split takes place, the function starts all over.
Need to also check the length of each query word:
<div class="search">aa ab ac ad</div>
<div class="search">ab ba bb bc</div>
<div class="search">bb cc dd ee</div>
<script>
function search(query) {
var divs= document.getElementsByTagName('div');
var words = query.toLowerCase().split(" ");
for (var h = 0, len = divs.length; h < len; ++h) {
for (var i = 0; i < words.length; i++) {
if (words[i].length > 0 && divs[h].innerHTML.indexOf(words[i]) >= 0) {
divs[h].style.backgroundColor = '#ddd';
break;
}
else {
divs[h].style.backgroundColor = '#fff';
}
}
}
}
</script>
<input type="text" onkeyup="search(this.value);">
Try my code :
HMTL :
<div class="search">
<div>aa cC abcc ac ad</div>
<div>ab ba bb bcc</div>
<div>bb cc dd ee cc</div>
</div>
<span>Search: </span><input type="text">
CSS :
div{
border:solid 1px #1e2a29;
margin-bottom:10px;
padding:5px;
width:auto;
}
.matched{
background-color:#f8dda9;
border:1px solid #edd19b;
margin:-1px;
border-radius:2px;
}
input[type="text"]{
margin-left:10px;
}
Javascript :
$(document).ready(function(){
$('.search > div ').each(function(i, el){
$(this).data('originalText', $(this).html());
});
$('input').keyup(function(e){
var _val = $(this).val();
var _span = '<span class="matched" >$1</span>';
$('.search div ').each(function(i, el){
var _originalVal = $(el).data('originalText');
var re = new RegExp('('+_val+')', "ig");
if(_val.length > 1 && re.test(_originalVal) >=0 ){
$(el).html(_originalVal.replace(re, _span));
}else{
$(el).html(_originalVal);
}
});
});
})
See DEMO

Categories

Resources