Intended outcome: The user inputs any characters from the keyboard. They will then be used to check if the inputted string is a word from the Dictionary API. If they match with each other, the string will be in the <p> element. If not, then the inputted string will go through anotherFunction().
Questions:
keyboard.event, but not in the <input> / <textarea>, for the fetchApi() to be able to search for a real word from a string, instead of each inputted character? (Like I do not want that only until the user types the word and press Enter, then the API starts kicking in)Thank you again, and again. Thanks a lot!
var characters = '';
var text = document.getElementById("text");
var word = result[arg0].word;
document.addEventListener('keydown', function(input) {
if (input.key >= 'a' && input.key <= 'z') {
fetchApi(input.key);
}
});
function fetchApi(word) {
let url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;
fetch(url).then(res => res.json()).then(result => data(result, word));
}
function data(result, word) {
if (input.key == word) {
characters += input.key;
text.innerHTML = characters;
}
else {
text.innerHTML = anotherFunction();
}
}
<p id="text"></p>
I hope I understand your question right but I think what you want is:
<input> or <textarea> instead of the document. Explained heretext.addEventListener('keydown', function(input) {
if (input.key >= 'a' && input.key <= 'z') {
fetchApi(input.key);
}
});
Enter key. For this you could either simply get the value of the <input> and send it directly to the API (text.value). Or if you want to filter the characters before (and change as little code as possible from your existing solution) you could also send your characters string to it. (Like the code below)let inputWord = ""
text.addEventListener('keydown', function(input) {
if (input.key >= 'a' && input.key <= 'z') {
inputWord += input.key; // add each character to string if it's between a-z
} else if (input.key === "Enter") { // on enter fetch the entire inputWord
fetchApi(inputWord);
inputWord = "" // clear inputWord after Enter (but not in <input>)
}
});