I have a div with a handful of spans, each span containing one word. The user can tap/click a word to select it, but I’m also trying to implement keyboard input.
I’d like to highlight each letter in any matching words as the user types.
For example, let’s say we have these five words:
banana
cat
baby
ball
candy
If the user types "ba" I’d like to highlight the first two letters in "banana" , "baby" , and "ball" (then if they type an ‘n’, it would un-highlight the letters in "baby" and "ball" and would highlight the first three letters of "banana" only)
These words are all dynamically generated from a word list array, so I’m hoping there might be a way to achieve this highlighting without having to wrap every single letter in a span.
Is this possible?
2
Answers
To prevent the addon of span element:
You may use the linear-gradient css style to highlight specific letter sequence. Please modify the code below to cope with your need since you may need to highlight multiple letters occurrences within a span element.
You can get the text and input and then split the text into words using split(), then iterate over that array and check if the value startsWith() whatever string the input is passing during an input eventListener. Placing the logic in a map method you can reformat the searched string and concatenate the leftover part of the word using substring() or splice(). Join the mapped array and then set the elements innerHTML to the newly formatted string with a
highlight
class.See further comments in the code snippet