var userNames = $('.username').map(function(index){
return $(this).text().replace(/\s/g,'');
});
userNames = $.unique(userNames).toArray();
var a = document.getElementById('text_editor_textarea');
var sc= $(a).data('sceditor');
var updateText = function() {
sc ? sc.bind('keypress',sc.updateOriginal).blur(sc.updateOriginal) : setTimeout(updateText,200);
};
updateText();
sc.bind('keypress',function(e) {
if(e.shiftKey && e.which === 64){
sc.unbind('keypress');
sc.bind('keyup',function(e) {
var string = e.which;
var stringCase = String.fromCharCode(string);
var word=[];
if(stringCase !== " " || e.which !== 32) {
word.push(stringCase);
} else if(e.which === 8){
word.pop();
} else {
return;
}
console.log(word);
});
}
});
What I am trying to do is when the user presses SHIFT+2 creating the # symbol it then starts adding to an array, multiple problems exist in my code right now. When console.logging the array it does this
["2"]
[" "]
["M"]
["Y"]
[" "]
["W"]
["O"]//.etc
First off in my code I write if(stringCase !== " " || e.which !== 32) { so basically that if it is not a space or blank then to add it (.push(stringCase) ) and then I check if the keycode is backspace 8 and if it is pop the array word. Else return it.
For a quick example http://jsbin.com/erebey/1/edit
Basically I want it to do what it does on SO when typing #USERNAME where the div appears with the usernames name and once you click it it adds that to the textarea.
Related
What I'm trying to achieve is to read the current word at the caret position.
Example:
Hello| -> returns Hello
Hel|lo -> returns Hello
I have put the code inside an event handler which is onKeyup inside an if statement:
if( e.keyCode === 37 || e.keyCode === 39 ){
console.log($(this).getWord());
}
When this is executed, it returns the current word, but the text area loses the focus.
Jsfiddle
How is this supposed to work?
Type word in the text area then click on left or right arrow keys, the current word will get displayed.
I would use textArea.selectionStart instead of mucking with mutating the selection itself. This will work for you if Internet Exploder < 8 compatibility isn't a concern.
var $mytextarea = $('#mytextarea');
$mytextarea.keyup(function(e) {
if (e.keyCode === 37 || e.keyCode === 39) {
$("#current").text(getWord());
}
});
function getWord() {
var textarea = $mytextarea[0],
pos = textarea.selectionStart,
raw = textarea.value,
start = pos,
end = pos;
while (raw.charAt(start) !== ' ' && start > 0) {
start--;
}
while (raw.charAt(end) !== ' ' && end < raw.length) {
end++;
}
return raw.substring(start, end);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="mytextarea">The quick brown fox jumps over the lazy dog.</textarea>
<div>
the current word is <span id="current"></span>
</div>
I changed your code a bit. It no longer manipulates the cursor which means response time is a lot faster.
Here is your updated code:
$('#mytextarea').keyup(function (e) {
//if (e.keyCode === 37 || e.keyCode === 39) {
//get cursor position
var caret = getCaretPosition(this);
//get the end index of current word
var endOfWord = this.value.slice(caret.end).match(/(\s|$)/i).index + caret.end;
//get current word
var word = /\S+$/.exec(this.value.slice(0,endOfWord));
//make sure word is not null
word = word ? word[0] : '';
//remove punctuation
word = word.replace(/(\.|\!|,|;|:|\(|\)|\{|\}|\[|\]|'|"|-$)/,'');
$("#current").text(word);
//}
});
function getCaretPosition(ctrl) {
var start, end;
if (ctrl.setSelectionRange) {
start = ctrl.selectionStart;
end = ctrl.selectionEnd;
} else if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
start = 0 - range.duplicate().moveStart('character', -100000);
end = start + range.text.length;
}
return {
start: start,
end: end
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="mytextarea"></textarea>
<div>
the current word is <span id="current"></span>
</div>
I do want to point out this is not my code and was copied from this fiddle.
I'm trying to capture the character just entered into a <textarea>, but I can only get which key is pressed via key event like keydown or keyup, not knowing if it's lower case or upper case.
For example, when I input A or a, the event key codes for keydown are all 65.
I thought of using val() to get the string in the <textare> and get the last character of it, but that is too slow and memory consuming, since I want to record every keyboard event while the user is typing.
So is there a way I can simply get the last entered character?
Try this:
var p = $('#log')[0];
$("#textarea").on("keypress", function(e) {
p.textContent = '';
var k = e.keyCode || e.which;
var character = String.fromCharCode(k);
if (!isNaN(character * 1)) {
p.textContent += 'character is numeric';
} else {
if (character == character.toUpperCase()) {
p.textContent += 'UPPER case true';
}
if (character == character.toLowerCase()) {
p.textContent += 'lower case true';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea"></textarea>
<p id="log"></p>
I see what you mean about the shiftKey
var myObj = $('#myTextarea');
function isLetter(char){
if ((char.toLowerCase() !== char) || (char.toUpperCase() !== char)) {
return true;
}
return;
}
myObj.keypress(function( event ){
var text = myObj.val();
var char = text.charAt(text.length-1);
if (!event.shiftKey && isLetter(char)) {
if (char == char.toUpperCase()) {
console.log('Upper');
}
if (char == char.toLowerCase()) {
console.log('Lower');
}
}
});
try:
<textarea id="area1"></textarea>
window.onload = function () {
document.getElementById("area1").onkeypress = function(event){
var code = event.which;
if ((code >= 65) && (code <= 90)) {
alert('Upper');
}
else if ((code >= 97) && (code <= 122)) {
alert('Lower');
}
}
}
I am trying to make a typing game in javascript with jQuery but facing a issue.
How can I highlight the character the user types when they type it?
I have example in my div
<div id="theWord">tjurkey</div>
When the user starts typing "tj.." it should highlight t, then j, as they type it.
Currently I am stuck here:
$("body").keypress(function(e) {
if (e.which !== 0) {
var t = String.fromCharCode(e.which);
if ( t != undefined){ wordContainer += t.replace("undefined",""); }
if ( wordContainer == theWord){
alert("You typed the word" + theWord);
}
}
});
Ex. the word is "Tjurkey", if user start typing P it shouldn't highlight anything, because It's TJurkey and not P.
If user types "T" to start with it should highlight the "T" like Tjurkey, if user type "a" after that it shouldn't highlight it, because the word is Tjurkey and not Ta.... when the user then type j it should hightlight the j, because the word is TJ...urkey.. got the point?
Demo: http://jsfiddle.net/cVaHb/
var $target = $('#theWord'),
t = ''
$("body").keypress(function(e) {
if (e.which !== 0) {
t += String.fromCharCode(e.which);
var text = $target.text(),
pos = text.search(t);
if(pos > -1){
$target.html(
text.substring(0,pos)
+'<span class="highlight">'+t+'</span>'
+text.substring(pos+t.length)
);
}else{
$target.text(text);
}
}
});
CSS:
.highlight {
background: yellow;
}
Edit: If you want to ignore wrong letters, you can use
var $target = $('#theWord'),
t = ''
$("body").keypress(function(e) {
if (e.which !== 0) {
var newt = t + String.fromCharCode(e.which);
var text = $target.text(),
pos = text.search(newt);
if(pos > -1){
t = newt;
$target.html(text.substring(0,pos)+'<span class="highlight">'+t+'</span>'+text.substring(pos+t.length));
}
}
});
Demo: http://jsfiddle.net/cVaHb/1/
Here, to get you started
var t = "";
var word = $("#theWord").text();
$("body").keypress(function (e) {
if (e.which !== 0) {
t += String.fromCharCode(e.which);
if (word.substring(0, t.length) == t) {
$("#theWord").html("<span class='highlight'>" + t +"</span>"+ word.substring(t.length));
}
else
{
t=t.substring(0,t.length - 1);
}
}
});
check it out here:
http://jsfiddle.net/zahirdhada/UBbF7/1/
You can get the typed characters and find the starting and ending points of those in your string. Then you have to wrap that text with a span
ex: if user typed tj you should write a script to fill
<div id="theWord"><span style="color:red">tj</span>urkey</div>
I have an input field that the user will fill in and I want to automatically capitalize the first letter of each word as they're typing. However, if they manually delete a capital letter and replace it with a lower case, I want that to remain (basically capitalizing the letters is what we recommend, but not required). I'm having trouble implementing something that will leave the letters they manually typed alone and not change them.
Here is the code I have along with a Jsfiddle link to it.
<input class="capitalize" />
and JS:
lastClick = 0;
$(document).ready(function() {
$(".capitalize").keyup(function() {
var key = event.keyCode || event.charCode;
if (!(lastClick == 8 || lastClick == 46)) {
//checks if last click was delete or backspace
str = $(this).val();
//Replace first letter of each word with upper-case version.
$(this).val(str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}));
}
lastClick = key;
});
});
I haven't allowed for preserving the user's manual corrections, but as it is you can see in the jsfiddle that the input jumps around and doesn't work correctly. Can anyone help me or recommend a best way to do this? Thank you.
$(document).ready(function() {
var last;
$(".capitalize").on('keyup', function(event) {
var key = event.keyCode || event.which,
pos = this.value.length,
value = this.value;
if (pos == 1 || last == 32 && (last !== 8 || last !== 46)) {
this.value = value.substring(0, pos - 1) +
value.substring(pos - 1).toUpperCase();
}
last = key;
});
});
http://jsfiddle.net/userdude/tsUnH/1
$(document).ready(function() {
$(".capitalize")
.keyup(function(event) {
var key = event.keyCode || event.charCode;
// store the key which was just pressed
$(this).data('last-key', key);
})
.keypress(function(event) {
var key = event.keyCode || event.charCode;
var lastKey = $(this).data('last-key') ? $(this).data('last-key') : 0; // we store the previous action
var $this = $(this); // local reference to the text input
var str = $this.val(); // local copy of what our value is
var pos = str.length;
if(null !== String.fromCharCode(event.which).match(/[a-z]/g)) {
if ((pos == 0 || str.substr(pos - 1) == " ") && (!(lastKey == 8 || lastKey == 46))) {
event.preventDefault();
$this.val($this.val() + String.fromCharCode(event.which).toUpperCase());
}
}
// store the key which was just pressed
$(this).data('last-key', key);
});
});
I have updated your fiddle http://jsfiddle.net/nB4cj/4/ which will show this working.
I need functionality that textarea should contain max 5 lines and
each line should contain max 15 chars, when user writes 2 words
e.g. 123456 123456789 and if that line char limit exceeds 15, then
it should bring the 2nd word in next line along with \n char in first line
(means 123456 will be in first line along with \n and 123456789 will be in 2nd)
,
I need to maintain \n(replacing <br>) in my db for some reasons.
i wrote this code, which gives fuzzy result in some conditions
<textarea onkeypress="charCountTextarea('txt1',event,'75','14')" id="txt1"></textarea>
var countLines=0;
var newLines;
function charCountTextarea(textAreaId,e,limit,lineLen)
{
newLines = $("#"+textAreaId).val().split("\n").length;
var t = $("#"+textAreaId)[0];
var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;
//console.log("new lines"+lineIndex);
if(newLines >= 5 && $("#"+textAreaId).val().split("\n")[lineIndex].length>lineLen)
{
if( e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
{
e.preventDefault();
return false;
}
}
else
if($("#"+textAreaId).val().split("\n")[lineIndex].length>=lineLen) // which will count the total line char condition
{
console.log($("#"+textAreaId).val().split("\n")[lineIndex][lineLen-1]);
if($("#"+textAreaId).val().split("\n")[lineIndex][lineLen-1].indexOf(" ")==-1 && e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && lineIndex != 4 && newLines<5)
{
// to bring the word in next line
var str = $("#"+textAreaId).val(), replacement = '\n';
str = str.replace(/ ([^ ]*)$/,replacement+'$1');
$("#"+textAreaId).val(str);
}
else
if(e.keyCode!=8 && e.keyCode!=46 && e.keyCode!=33 && e.keyCode!=34 && e.keyCode!=35 && e.keyCode!=36 && lineIndex!=4 && newLines<5)
{
// to insert next line
insertTextAtCaret(document.getElementById(textAreaId), "\n");
}
}
if(e.keyCode == 13 && newLines >= 5)
{
//linesUsed.css('color', 'red');
e.preventDefault();
return false;
}
}
function charCountTextarea(textAreaId,e,limit,lineLen)
{
var code = e.charCode || e.keyCode;
newLines = $("#"+textAreaId).val().split("\n").length;
var t = $("#"+textAreaId)[0];
var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;
console.log('val t :'+$("#"+textAreaId).val()+' line index : '+lineIndex+' new lines '+newLines);
if(lineIndex == 10 && $("#"+textAreaId).val().split("\n")[lineIndex].length>(lineLen+1) && code!=8 && code!=46 && code!=33 && code!=34 && code!=35 && code!=36 && code!=37 && code!=38 && code!=39 && code!=40)
{
$("#"+textAreaId).val(($("#"+textAreaId).val()).substring(0, $("#"+textAreaId).val().length - 1));
alert('You are reached to limit');
return false;
}
if(lineIndex<5)
{
$("#"+textAreaId).val($("#"+textAreaId).val().wordWrap(lineLen, "\n", 0));
}
var countLine1 = $("#"+textAreaId).val().split("\n")[0].length;
if($("#"+textAreaId).val().split("\n")[lineIndex].length>lineLen) // which will count the total line char condition
{
console.log("In condition : ");
if(code!=8 && code!=46 && code!=33 && code!=34 && code!=35 && code!=36 && code!=37 && code!=38 && code!=39 && code!=40)
{
// to insert next line
insertTextAtCaret(document.getElementById(textAreaId), "\n");
}
}
}
You can not know if the input will be fed using keyboard. I could just use the mouse to paste a text there.
I would rely on a function that would constantly check the input and take the action you want, which I would execute using the setInterval() function once the textarea is focused, which then gets cleared using clearInterval() once the textarea loses focus.
And this function would use a RegExp to process the input and split it into necessary lines.
EDIT: Here's what I mean.
$('body').on('focus','#txt1',function(e) {
$(this).data('int',setInterval(checkInput,1));
}).on('blur','#txt1',function(e) {
clearInterval($(this).data('int'));
$(this).removeData('int');
});
function checkInput() {
var val = $('#txt1').val();
// process val here
$('#txt1').val(val);
}