I have used a code that show the line number from textarea and it works with me.But i would like to show a string beside that so the output will be:
Line number: 3
here is the code that I have used:
http://jsfiddle.net/S2yn3/1/
and the function is:
$(function() {
$('#test').keyup(function() {
var pos = 0;
if (this.selectionStart)
pos = this.selectionStart;
} else if (document.selection) {
this.focus();
var r = document.selection.createRange();
if (r == null) {
pos = 0;
} else {
var re = this.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
pos = rc.text.length;
}
}
$('#c').html(this.value.substr(0, pos).split("\n").length);
});
});
Thanks guys
Your code is counting the number of '\n' characters from the first character to the cursor. If you're looking for the total number of linebreaks, change...
$('#c').html(this.value.substr(0, pos).split("\n").length);
to
$('#c').html('Line no. ' + this.value.split("\n").length);
Related
I'm building a simple text editor and I start with basics - as user press enter and start a new line a want to insert br to the the second textbox. The second textbox is meant to send ready formatted text to the database. As of now I managed to copy data from first to second textbox as user typing. Hence, I want to disable viewing br in the first textbox. Is there a way not to display br in the first textbox but technically have it. Thank you in advance!
DEMO: https://jsfiddle.net/mxr7hz3p/
Textboxes:
<textarea type="text" id="first"></textarea>
<textarea type="text" id="second"></textarea>
JS:
$(function (){
$('#first').keyup(function (e){
if(e.keyCode == 13){
var curr = getCaret(this);
var val = $(this).val();
var end = val.length;
$(this).val( val.substr(0, curr) + '<br>' + val.substr(curr, end));
}})
});
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
}
else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
$('#first').keyup(function(){
$('#second').val(this.value);
});
You can simplify the JS in the fiddle to do this
$('#first').keyup(function(){
var val = $(this).val();
val = val.replace(/\n/g, '<br />')
$('#second').val(val);
});
https://jsfiddle.net/t3vzgnp7/2/
I wanted to get current cursor position in a textbox using JQuery. Cursor position may change using keyboard arrow keys, while typing or mouse press. Is there a way to get this done.
var currentCursorPosition = $("#textbox").currentCursorPosition();
With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
source: Caret position in textarea, in characters from the start
Fiddle: This solves my problem.
<textarea id="textarea" style="width:80%;height:100px;"></textarea><br/>
<input type="text" id="indicator" style="width:30px;">
JavaScript:
var indicator = document.getElementById("indicator");
var textarea = document.getElementById("textarea");
setInterval(function() { indicator.value = caret(textarea);}, 100);
function caret(node) {
if(node.selectionStart) return node.selectionStart;
else if(!document.selection) return 0;
//node.focus();
var c= "\001";
var sel= document.selection.createRange();
var txt= sel.text;
var dul= sel.duplicate();
var len= 0;
try{
dul.moveToElementText(node);
}
catch(e){
return 0;
}
sel.text= txt + c;
len= (dul.text.indexOf(c));
sel.moveStart('character',-1);
sel.text= "";
return len;
}
Source: Source page
Ok I am making a text editor and have to try and make the last word typed change font color based on if it's a keyword or not... I have tried multiple solutions to this but nothing has prevailed... Here is what I have tried so far
function getLastWord() {
var input = document.getElementById("my_text").value;
//var input = document.getElementById(textArea.value);
var inputValue = input.value;
var lastWordTyped
var changeColorOfWord;
var ele = document.querySelector("#my_text");
//ele.style.color = "blue"
if (input == null) {
input == " ";
}
lastWordTyped = input.substr(input.trim().lastIndexOf(" ") + 1);
//lastWordTyped = inputValue.substr(inputValue.trim().lastIndexOf(" ") + 1);
if (input != null) {
for (var i = 0; i < reservedKeyWords.length; i++) {
if ( lastWordTyped == reservedKeyWords[i] ) {
//changeColor(lastWordTyped);
//my_text.replace(inputValue, lastWordTyped);
//ele.fieldNameElement.innerHTML = lastWordTyped;
//ele.innerHTML = lastWordTyped;
ele.innerHTML.fontcolor = 'Blue';
return;
} else if (lastWordTyped !== reservedKeyWords[i]) {
//ele.innerHTML = ele.innerHTML.replace(lastWordTyped, '<span style="color:black"></span>');
//resetFontColor();
}
}
}
}
I have tried this function (found from SO)
function changeColor(word) {
var ele = document.querySelector("my_text");
ele.onkeypress = function () {
setTimeout(function () {
//the setTimeout is so the content is inserted before execution
document.getElementById('view_text').value = ele.textContent;
if (ele.innerHTML.indexOf(word) !== -1) {
ele.innerHTML = ele.innerHTML.replace(word, '<span style="color:blue">' + word + '</span>');
}
}, 50);
}
}
Also I have tried this one:
function colorMyKeyword(keywordColor, text) {
return '<span style="color:' + keywordColor + '>' + text + '</span>';
}
None of these functions have gotten the job done though. I have it now so that it will change the text color to blue but then the problem is that it changes ALL of the text to blue after that word...
I would prefer this to be in javascript as I do not know how to use JQuery, or really CSS for that matter or even know how to write it..
Thank you for any responses.
Updated code based on comment(s) below (changed to div from input)
Not the best code in the world but it should work. The CSS should probably be done by adding a class instead of changing the style attribute.
<div id="my_text">This is some text</div>
var isKeyword = false;
var el = document.getElementById('my_text');
var arr = el.innerHTML.split(' ');
var lastWordTyped = arr.pop();
/* replace with yours*/
var reservedKeyWords = ['text','another','word', 'here'];
for (var i = 0, len = reservedKeyWords.length ; i < len ; i++) {
if ( lastWordTyped == reservedKeyWords[i] ) {
lastWordTyped = '<span style="color:blue">'+lastWordTyped +'</span>'; //update color
arr.push(lastWordTyped);
isKeyword = true;
}
}
if (!isKeyword) { arr.push(lastWordTyped); } //put original back
el.innerHTML = arr.join(' ');
UPDATED: Do the whole thing on keyup
here's a simple example that you can use: DEMO
$('#text').keyup(function(){
$('#result').html($('#text').val());
var splittedText=$('#result').html().split(/\s/);
var lastWord=splittedText[splittedText.length-1];
$('#result').html($('#result').html().replace(lastWord,'<span>'+lastWord+'</span>'));
$('#result').children('span').css('color',$('#color').val());
});
you need to write a sentence in the first input and a hexa-deciaml color in the second one.(including the # at the beginning)
Here is an attempt to answer your questions :
I am using #GaryStorey's answer as it was a better starting point than what I add (I do like pop&push).
The problem with his answer were that it only showed how to change the color but it wasn't relevant on how to do it in an input nor in a contenteditable element.
So here are my adjustements, with a setCaret function to deal with the fact that caret always returns to start if we do change the innerHTML of edited element.
Be carefull, it is still very buggy and you should not use it in any production,
however it can give you a good starting point.
var reservedKeyWords = ['text', 'another', 'word', 'here'];
var el = document.getElementById('my_text');
el.addEventListener('keyup', function (evt) {
if (evt.keyCode == 32 || evt.keyCode == 13) {
var isKeyword = false;
var arr = el.innerHTML.split(/\s/);
var lastWordTyped = arr.pop();
lastWordTyped = lastWordTyped.replace(' ', '');
for (var i = 0, len = reservedKeyWords.length; i < len; i++) {
if (lastWordTyped == reservedKeyWords[i]) {
lastWordTyped = '<span style="color:blue">' + lastWordTyped + '</span>'; //update color
arr.push(lastWordTyped);
isKeyword = true;
}
}
if (!isKeyword) {
arr.push(lastWordTyped);
} //put original back
el.innerHTML = arr.join(' ') + ' ';
setCaret(el);
}
});
function setCaret(el) {
var range = document.createRange();
var endNode = el.lastChild;
range.selectNodeContents(endNode);
range.setStart(endNode, range.endOffset);
range.setEnd(endNode, range.endOffset);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
#my_text {
min-width: 100%;
min-height: 2em;
padding: 0.5em;
display: block;
border : dashed 0.5px grey;
}
<p> list of KeyWords : 'text', 'another', 'word', 'here';</p>
<span id="my_text" contenteditable="true">Edit me using "reservedKeyWords" defined in JS</span>
Oh and note that I am using a span instead of a div, because div tag adds some <br> from nowhere after the textNode.
What I need is this. I need a function that gets position of cursor in textarea and check if surrounding characters are "<" and ">" (without ""). I have a function that gets caret position
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
So this is example:
<textarea>
<paragraph>Text goes here.</paragraph>
<picture>Picture</picture>*(* is caret)
</textarea>
function xyz(){
var i=getCaret(textarea);
var previous_character=textarea.value(i-1);
var next_character=textarea.value(i+1);
if(previous_character==some_character and next_character==some_character){
do something...
}
}
You can get the the characters using String objects charAt function (character at)
var previous_character=textarea.value.charAt(i-1);
var next_character=textarea.value.charAt(i); // i will give you the next
I have a textarea with limited characters per line. Its function fine.
function limitRow(){
var count = 1;
var charsPerLine = row; // 30 characters
var maxLines = 20;
$('.AD_Text_textarea').keydown(function (e) {
var v = $(this).val(),
vl = v.replace(/(\r\n|\n|\r)/gm, '').length,
lineCount = $(this).val().split("\n").length;
if (parseInt(vl / count) >= charsPerLine) {
if (lineCount >= maxLines) {
return false;
}
$(this).val(v + "\n");
count += 1;
}
});
}
My question is, if Iam going to line 1, after typing for example 4 rows text and type on for example cursor position 4 some text, then the line counter counts of the beginning and breaks the line after 60 characters and jumps on the end of line 4.
How can I resolve this problem?
I hope, it was clear. (Iam sorry for my english)
try this
var count = 1;
var charsPerLine = 30; // 30 characters
var maxLines = 2;
$('.AD_Text_textarea').keydown(function (e) {
var this_input = $(this);
var value = this_input.val().split('\n');
if (value.length < maxLines) {
if (value[parseInt(value.length) - 1].toString().length > charsPerLine) {
alert(value.length.toString());
this_input.val(this_input.val() + '\n');
}
}
else {
return false;
}
});