Highlighting characters in an HTML element on keypress - javascript

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>

Related

Removing < > symbols while typing in javascript

I have developed following code. But while typing i need to remove < > these two charectres. Its removing but it removing entire string when we type in middle. I donr want to remove entire string i want remove only < > while typing.
Enter your name:
<input type="text" id="UserC" onkeyup="rem()">
function rem() {
var spclChars = "<>"; // specify special characters
var content = document.getElementById("UserC").value;
for (var i = 0; i < content.length; i++) {
if (spclChars.indexOf(content.charAt(i)) != -1) {
document.getElementById("UserC").value = "";
return false;
}
}
}
You can use regex for that:
var str = 'hello<name>'
function rem(string) {
return string.replace(/<|>/g, '')
}
console.log(rem(str))
this will output helloname.
Use the below code it's working perfectly...
$(document).on('keypress', "#inputid", function(e) {
var check_val = $("#inputid").val();
if ((e.which == 60 || e.which == 62)) { // &lt ascii value is 60 and &gt ascii value is 62
console.log(check_val);
// $(this).attr("placeholder", "digits only");
// $(this).addClass("alert-danger");
$(this).val(check_val);
return false;
} else {
$(this).removeClass("alert-danger");
}
});

Autocomplete usernames when TAB is pressed

I'm working on a "autocomplete usernames when TAB is pressed" feature.
I've been able to detect # and to search in a username list.
How to perform the autocompletion now, with a different matching username each time we press TAB ?
var userlist = ['bonjour', 'bleuet', 'bonobo', 'coucou'];
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
}
}
$('#writing').keydown(function(e) {
if (e.keyCode == 9) {
var caret = getCaretPosition(this);
var word = /\S+$/.exec(this.value.slice(0, this.value.indexOf(' ',caret.end)));
word = word ? word[0] : null;
if (word.charAt(0) === '#')
alert(userlist.filter((x) => x.indexOf(word.slice(1)) === 0));
e.preventDefault();
return false;
}
});
#writing { width: 500px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="writing">Hello #b what's up? hello #you as well... Type #b and then "TAB" key it should autocomplete usernames
</textarea>
Here is the solution for your issue:
I used .on() to bind keydown to textbox, rather than keypress.
var userlist = ['bonjour', 'bleuet', 'bonobo', 'coucou'];
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
}
}
$('#writing').keydown(function(e) {
if (e.keyCode == 9) {
var caret = getCaretPosition(this);
var word = /\S+$/.exec(this.value.slice(0, this.value.indexOf(' ',caret.end)));
word = word ? word[0] : null;
if (word.charAt(0) === '#')
//alert(userlist.filter((x) => x.indexOf(word.slice(1)) === 0));
var stringParts = $(this).val().split('#');
var nameToInsert = userlist.filter((x) => x.indexOf(word.slice(1)) === 0)[0];
var completeString = stringParts[0] + '#' + nameToInsert;
$(this).val(completeString);
e.preventDefault();
return false;
}
});
#writing { width: 500px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="writing">Hello #b what's up? hello #you as well... Type #b and then "TAB" key it should autocomplete usernames
</textarea>
Now it completes the name. But I would work on improving on the algorithm predicting the name.
Here's a very basic example that works in modern browsers (Chrome, Firefox, Edge):
const users = ['asdasd', 'fgsfds', 'Foobar']
const input = document.getElementById('input')
const patt = /\S+$/
input.addEventListener('keydown', e => {
if (e.key !== 'Tab') {
return
}
e.preventDefault()
const start = input.selectionStart
const seg = input.value.slice(0, start)
const match = (seg.match(patt) || [])[0]
if (!match) {
return
}
const idx = users.findIndex(x => x.startsWith(match))
if (idx < 0) {
return
}
const replace = users[users[idx] === match ? (idx + 1) % users.length : idx]
const newSeg = seg.replace(patt, replace)
input.value = newSeg + input.value.slice(start)
input.setSelectionRange(newSeg.length, newSeg.length)
})
<input type="text" id="input" size="50" value="bla asd bla fgs">
It cycles through the names and works at any point in the line. Support for older browsers can be added with Babel and es6-shim.
Replace keypress with keydown. Keypress doesn't fire when tab is pressed, I guess because tab gets input out of focus.
EDIT:
Not perfect, gets undefined sometimes, but you can work from here
EDIT:
ok don't mind this, it's half done and #slikts solution is obviously better, made from scratch and all.
var userlist = ['bonjour', 'bleuet', 'bonobo', 'coucou'];
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
}
}
function setCaretPosition(elem, caretPos, caretPosEnd) {
caretPosEnd = caretPosEnd || caretPos;
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPosEnd);
}
else
elem.focus();
}
}
}
function getIndexCloserTo(str, char, ref) {
if(str.indexOf(char) == -1) return false;
//flip string and find char beggining from reference point
var nstr = str.split("").reverse().join("");
return str.length - 1 - nstr.indexOf(char, str.length - 1 - ref);
}
var lastWordToMatch = "";
var lastAddedWord = "";
var lastIndexUsed = 0;
$(document).ready( function() {
$('#writing').keydown(function(e) {
if (e.keyCode == 9) {
var caret = getCaretPosition(this);
//Get username input part, from the "#" closer to the cursor
//to the position of the cursor
var beginning = getIndexCloserTo(this.value, '#', caret.start);
if( beginning !== false){
var word = this.value.slice( beginning , caret.start);
word = word ? word[0] : null;
if (word.charAt(0) === '#'){
//Get array of names that match what is written after the #
var usermatches = userlist.filter((x) => x.indexOf(word.slice(1)) === 0);
//Check if any matches were found
if( usermatches.length > 0 ){
//If the word is the same as last time, use the next match
if( word == lastWordToMatch ){
//use mod to circle back to beginning of array
index = (lastIndexUsed + 1 ) % usermatches.length;
lastIndexUsed = index;
} else {
//otherwise get first match
index = 0;
lastWordToMatch = word;
}
var text = this.value;
//Remove #
word = word.slice(1);
//replace the portion of the word written by the user plus the
//word added by autocompletion, with the match
$(this).val(text.replace(word+lastAddedWord, usermatches[index]) );
//save the replacement for the previous step, without the user input
//just what autocompetion added
lastAddedWord = usermatches[index].replace(word, '');
//put cursor back where it was
setCaretPosition(this,caret.start);
}
}
}
e.preventDefault();
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="writing">Hello #b what's up? hello #you as well... Type #b and then "TAB" key it should autocomplete usernames
</textarea>

How do I know, via key event code, if the character just entered in a <textarea> is lower or upper case?

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');
}
}
}

Capitalize first letter of words in sentence, except on manual replacement

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.

Convert first letter to uppercase on input box

JS Bin demo
This regex transform each lower case word to upper case. I have a full name input field. I do want the user to see that each word's first letter he/she pressed is converted to uppercase in the input field.
I have no idea how to properly replace the selected characters in the current input field.
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val(),
regex = /\b[a-z]/g;
val = val.toLowerCase().replace(regex, function(letter) {
return letter.toUpperCase();
});
// I want this value to be in the input field.
console.log(val);
});
Given i.e: const str = "hello world" to become Hello world
const firstUpper = str.substr(0, 1).toUpperCase() + str.substr(1);
or:
const firstUpper = str.charAt(0).toUpperCase() + str.substr(1);
or:
const firstUpper = str[0] + str.substr(1);
input {
text-transform: capitalize;
}
http://jsfiddle.net/yuMZq/1/
Using text-transform would be better.
You can convert the first letter to Uppercase and still avoid the annoying problem of the cursor jumping to the beginning of the line, by checking the caret position and resetting the caret position. I do this on a form by defining a few functions, one for all Uppercase, one for Proper Case, one for only Initial Uppercase... Then two functions for the Caret Position, one that gets and one that sets:
function ProperCase(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.toLowerCase().replace(/^(.)|\s(.)|'(.)/g,
function($1) { return $1.toUpperCase(); });
$(el).val(s);
setCaretPosition(el,pos.start);
}
function UpperCase(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.toUpperCase();
$(el).val(s);
setCaretPosition(el,pos.start);
}
function initialCap(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.substr(0, 1).toUpperCase() + s.substr(1);
$(el).val(s);
setCaretPosition(el,pos.start);
}
/* GETS CARET POSITION */
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == 'number' && typeof el.selectionEnd == 'number') {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
/* SETS CARET POSITION */
function setCaretPosition(el, caretPos) {
el.value = el.value;
// ^ this is used to not only get "focus", but
// to make sure we don't have it everything -selected-
// (it causes an issue in chrome, and having it doesn't hurt any other browser)
if (el !== null) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', caretPos);
range.select();
return true;
}
else {
// (el.selectionStart === 0 added for Firefox bug)
if (el.selectionStart || el.selectionStart === 0) {
el.focus();
el.setSelectionRange(caretPos, caretPos);
return true;
}
else { // fail city, fortunately this never happens (as far as I've tested) :)
el.focus();
return false;
}
}
}
}
Then on document ready I apply a keyup event listener to the fields I want to be checked, but I only listen for keys that can actually modify the content of the field (I skip "Shift" key for example...), and if user hits "Esc" I restore the original value of the field...
$('.updatablefield', $('#myform')).keyup(function(e) {
myfield=this.id;
myfieldname=this.name;
el = document.getElementById(myfield);
// or the jquery way:
// el = $(this)[0];
if (e.keyCode == 27) { // if esc character is pressed
$('#'+myfield).val(original_field_values[myfield]); // I stored the original value of the fields in an array...
// if you only need to do the initial letter uppercase, you can apply it here directly like this:
initialCap(el);
} // end if (e.keyCode == 27)
// if any other character is pressed that will modify the field (letters, numbers, symbols, space, backspace, del...)
else if (e.keyCode == 8||e.keycode == 32||e.keyCode > 45 && e.keyCode < 91||e.keyCode > 95 && e.keyCode < 112||e.keyCode > 185 && e.keyCode < 223||e.keyCode == 226) {
// if you only need to do the initial letter uppercase, you can apply it here directly like this:
initialCap(el);
} // end else = if any other character is pressed //
}); // end $(document).keyup(function(e)
You can see a working fiddle of this example here: http://jsfiddle.net/ZSDXA/
Simply put:
$this.val(val);
$(document).ready(function() {
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
console.log(val);
$this.val(val);
});
});
As #roXon has shown though, this can be simplified:
$(document).ready(function() {
//alert('ready');
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
$this.val(val);
});
});
An alternative, and better solution in my opinion, would be to only style the element as being capitalized, and then do your logic server side.
This removes the overhead of any javascript, and ensures the logic is handled server side (which it should be anyway!)
$('input').on('keyup', function(event) {
$(this).val(function(i, v){
return v.replace(/[a-zA-Z]/, function(c){
return c.toUpperCase();
})
})
});
http://jsfiddle.net/AbxVx/
This will do for every textfield call function on keyup
where id is id of your textfield and value is value you type in textfield
function capitalizeFirstLetter(value,id)
{
if(value.length>0){
var str= value.replace(value.substr(0,1),value.substr(0,1).toUpperCase());
document.getElementById(id).value=str;
}
}
only use this This work for first name in capital char
style="text-transform:capitalize;
Like
<asp:TextBox ID="txtName" style="text-transform:capitalize;" runat="server" placeholder="Your Name" required=""></asp:TextBox>
$('.form-capitalize').keyup(function(event) {
var $this = $(this),
val = $this.val(),
regex = /\b[a-z]/g;
val = val.toLowerCase().replace(regex, function(letter) {
return letter.toUpperCase();
});
this.value = val;
// I want this value to be in the input field.
console.log(val);
});

Categories