Reputation: 31
I'd like to make effect above using input. I can make only change text color no matter what I put into inputbox, not specific letters. I'd like to make specific letters' color change what I write on the inputbox. For example, if I put "hello" into the inputbox, The colors of "H", "E", "L", "L", "O" turn green. here's my code below.
document.addEventListener("input", function() {
document.getElementById('values').style.color = "#999";
});
body {
font-family: sans-serif;
color: #222;
}
<body>
<h1 id="values"><span class="Q">Q</span><span class="W">W</span><span class="R">R</span><span class="T">T</span></h1>
<input type="text" id="inp">
</body>
</html>
Upvotes: 3
Views: 146
Reputation: 8316
Created a small snippet below to implement what you need I think :-
inp.addEventListener("input", function(e) {
const word = document.getElementById('values');
[...word.children].forEach((letter) => {
if (e.target.value.includes(letter.textContent)) {
letter.style.color = '#999';
} else {
letter.style.color = "#222";
}
})
});
body {
font-family: sans-serif;
color: #222;
}
<body>
<h1 id="values"><span class="Q">Q</span><span class="W">W</span><span class="R">R</span><span class="T">T</span></h1>
<input type="text" id="inp">
</body>
</html>
Explanation - We are getting the whole word
by getting the values
element since it's the parent of your letters
represented by individual span
elements. Then we are iterating over the children
of word i.e. for each letter
we are checking whether that's included in the text we just typed or not. If it is, style it to highlight color else to default color.
Note - Currently it's case-sensitive so q & Q are different (can be easily resolved by using .toUpperCase()/.toLowerCase()
on both sides of comparisons). Also it's searching for all occurrences of a letter so it will highlight all letters that match a particular letter from your input. So you would need additional logic to only highlight a single letter which hasn't been highlighted before.
Upvotes: 1
Reputation: 15767
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
$(function(){
$('#inp').on('keyup',function(e){
var key = e.keyCode || e.which;
key= String.fromCharCode(key);
$('.'+key.toString()).css({'color':'red'});
});
});
$(function(){
$('#inp').on('keyup',function(e){
var key = e.keyCode || e.which;
if(key != 8 && key != 16)
{
key= String.fromCharCode(key);
$('.'+key.toString()).css({'color':'red'});
}
});
});
body {
font-family: sans-serif;
color: #222;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<html>
<body>
<h1 id="values"><span class="Q">Q</span><span class="W">W</span><span class="R">R</span><span class="T">T</span></h1>
<input type="text" id="inp">
</body>
</html>
You can use jquery for this.DEMO
In this demo you can use both uppercase and lowercase letters.
Upvotes: 0