I'm looking for a way to change the letters in a text when you hover them.
After that, they will eventually not got back to normal and stay changed.
So I found a code to change the color of each letter of a text, but I'm looking for the same thing that picks the next leter in the alphabet.
Thanks a lot for the help.
$(document).ready(function(){
var letters = $('p').text();
var nHTML = '';
for(var letter of letters) {
nHTML+="<span class='x'>"+letter+"</span>";
}
$('p').html(nHTML);
})
.x:hover {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p>Hello World!</p>
I also found this code that let you change a text with an id.
I just don't know how to apply that to all my characters individually.
const $foo = $('#foo');
$foo.hover(function(){
$foo.text('Blah');
}, function(){
$foo.text('Foo');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
<li>Foo</li>
</nav>
Also, I have this script that can find the next letter.
function LetterChanges(str) {
var result = "";
for (var i = 0; i < str.length; i++) {
if (122 == str.charCodeAt(i)) {
result += "a";
} else if (90 == str.charCodeAt(i)) {
result += "A";
} else if ((65 <= str.charCodeAt(i) && str.charCodeAt(i) <= 89) || (97 <= str.charCodeAt(i) && str.charCodeAt(i) <= 121)) {
result += String.fromCharCode(str.charCodeAt(i) + 1);
} else {
result += str.charAt(i);
}
}
return result;
}
console.log(LetterChanges("AaZz+cod!foo"));
$('#result').html(LetterChanges("paul & rémi"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="result"></h1>
If I understand what you need, then this is the solution:
function nextLetter(ch) {
if (!ch.match(/[a-z]/i)) return ch;
else if (ch === 'Z') return 'A';
else if (ch === 'z') return 'a';
return String.fromCharCode(ch.charCodeAt(0) + 1);
}
$(document).ready(function(){
var letters = $('p').text();
var nHTML = '';
for(var letter of letters) {
nHTML+="<span class='x'>"+letter+"</span>";
}
$('p').html(nHTML);
$(".x").hover(function(e) {
if (e.type === "mouseenter") $(this).text(nextLetter($(this).text()));
});
})
Explanation:
nextLetter
checks whether it's a letter and does nothing if it's not a letter
if it's a Z or z, then will start over the alphabet, keeping the case
otherwise finds the next letter
the for cycle creates spans containing single letters, having the class of x
this is why the CSS hover rule works
we can create Javascript/jQuery events
I have created a Javascript event which changes the letter to the next one on hover
Fiddle: https://jsfiddle.net/1ar8uL4s/
Related
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)) { // < ascii value is 60 and > 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");
}
});
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 have a simple quesetion and I'm not sure why the array content is not being returned properly. I'm pretty sure this is something simple but somehow I'm not getting the results I want. The scenario is that a variable "compare" is set to a value e.g. "apple" and I am looping into the array, and, if apple matches an index print that into the text field. It doesn't do it and it always says the "not the same" value. For value dog it works. It seems like it reaches the last array then does comparisons. Help please.
Code below
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var text = "";
var i;
var arr = ["apple", "banana", "carrot", "dog"];
var compare = "apple";
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {text = "The value is " + arr[i] + "<br>"; }
else if (compare == "" || compare == null) { text = "The value is blank"; }
else if (arr[i] != compare) {text = "not the same"; }
else {text ="some error";}
}
document.getElementById("demo").innerHTML = text;
}
</script>
<p>Click the button to do a loop with a break.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
function print(msg) {
document.getElementById("demo").innerHTML += msg + '</br>';
}
function myFunction() {
var text = "";
var i;
var arr = ["apple", "banana", "carrot", "dog"];
var compare = document.getElementById('compare').value;
if (!compare) {
print('Compare is empty');
return;
} else {
print('Comparing with ' + compare);
}
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {
print("The value is at index " + i + " is " + arr[i]);
return; //results found, break out of the for loop
} else if (arr[i] != compare) {
print("not the same");
} else {
print("some error");
}
}
print("Could not find " + compare + " in array");
}
<!DOCTYPE html>
<html>
<body>
<script>
</script>
<p>Click the button to do a loop with a break.</p>
<input type="text" id="compare" placeholder="Compare to" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
For performance reasons it is better to validate the value of compare before the loop starts. You can break out of the loop using break, continue or return keywords.
It seems like it reaches the last array then does comparisons. Help please.
In effect, yes, because you never stop the loop. So all of the previous assignments you've done to document.getElementById("demo").innerHTML are overwritten by the final one.
If you want to stop when you find a match, use break to break out of the loop.
If you want the element to have a list of what had happened (which I think might be what you were trying to do, it's hard to tell), build the list up in text and then assign at the end:
if (compare == "" || compare == null) {
// Doesn't make sense to loop in this case, presumably
text = "The value is blank";
} else {
text = "";
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {
text += "The value matches " + arr[i] + "<br>";
// ^--- note the +=
} else {
text += "The value doesn't match " + arr[i] + "<br>";
// ^--- note the +=
}
}
}
document.getElementById("demo").innerHTML = text;
You never break the for loop. You must use break; to exit the loop when the if condition is met.
Here your is your solution: http://jsfiddle.net/urahara/rvLyfsto/
and your code:
function myFunction() {
var text = "";
var i;
var arr = ["apple", "banana", "carrot", "dog"];
var compare = "apple";
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {
text = "The value is " + arr[i] + "<br>";
break;
} else if (compare == "" || compare == null) {
text = "The value is blank";
break;
} else if (arr[i] != compare) {
text = "not the same";
break;
} else {
text = "some error";
break;
}
}
document.getElementById("demo").innerHTML = text;
}
Cheers!
I'm trying to find the keycodes (if that's even what I need) and to change the character to the incremented keycode (this is just for a coding challenge) and it's not working
function LetterChanges(str) {
var newString = "";
var keyCode;
for(var i = 0; i < str.length; ++i)
{
keyCode = str.charCodeAt(i);
console.log(keyCode);
if( keyCode > 57 && keyCode < 122)
{
//add 1 to the keycode
newString += String.fromCharCode(i+1);
//console.log(String.fromCharCode(i+1));
}
else if(keyCode === 90)
{
//if it's a z being examined, add an a
newString += "a";
}
else
//it is a symbol, so just add it to the new string without change
newString += str[i];
}
return newString.toUpperCase();
}
console.log(LetterChanges("Charlie"));
change
newString += String.fromCharCode(i+1);
to
newString += String.fromCharCode(keyCode+1);
Jsfiddle: http://jsfiddle.net/techsin/pnbuae83/1/
function codeIncreaser(input) {
var str='', code=null;
Array.prototype.forEach.call(input, function (e) {
code = e.charCodeAt();
if ((code>64 && code<90) || (code>96 && code<122)) {
code++;
} else if (code == 90) {
code = 65;
} else if (code == 122) {
code = 97;
}
str += String.fromCharCode(code);
});
return str;
}
var text = codeIncreaser('abczABC');
console.log(text);
This accommodates lowercase letters as well.
and if you wanna make code somewhat compact you could do something like this...
function $(i) {
var s='', c;
Array.prototype.forEach.call(i, function (e) {
c = e.charCodeAt();
((c>64&&c<90)||(c>96&&c<122))?c++:((c == 90)?c=65:(c==122&&(c=97)));
s += String.fromCharCode(c);
});
return s;
}
console.log($('abczABC #-#'));
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>