forked from Avdhesh-Varshney/WebMasterLog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
61 lines (55 loc) · 1.95 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const wordSearchForm = document.getElementById('word-search-form');
const copyBtn = document.getElementById('copy-btn');
const wordAppBody = document.querySelector('.word-app-body');
const wordListContainer = document.getElementById('word-list');
const loadingSpinner = document.getElementById('spinner');
let wordNotFound = true;
const getInputWord = () => {
wordSearchForm.addEventListener('submit', (event) => {
event.preventDefault();
let searchWord = wordSearchForm.search_word.value;
fetchSynWords(searchWord);
wordAppBody.style.display = "none";
});
}
getInputWord();
const fetchSynWords = async(searchWord) => {
let url = `https://api.datamuse.com/words?rel_syn=${searchWord}`;
try{
loadingSpinner.style.display = "flex";
let response = await fetch(url);
let fetchedData = await response.json();
loadingSpinner.style.display = "none";
renderWords(fetchedData);
} catch(error){
console.log(error);
}
}
const renderWords = (wordsArr) => {
let htmlCode;
if(wordsArr.length > 0){
wordNotFound = false;
htmlCode = wordsArr.map(word => {
return `<span class = "word-item"> ${word.word} </span>`;
});
wordListContainer.innerHTML = htmlCode.join("");
} else {
wordNotFound = true;
htmlCode = "No search results found!";
wordListContainer.innerHTML = htmlCode;
}
wordAppBody.style.display = "block";
}
const copyWordList = () => {
if(!wordNotFound){
let words = (wordListContainer.textContent).split(" ");
// removing the empty string element from the array
let filteredWords = words.filter(word => word.length !== 0);
// console.log(filteredWords);
let wordToCopy = filteredWords.join(", ");
navigator.clipboard.writeText(wordToCopy);
} else {
console.log("Nothing to copy");
}
}
copyBtn.addEventListener('click', copyWordList);