|
| 1 | +const container = document.querySelector(".container"), |
| 2 | + searchInput = container.querySelector("input"), |
| 3 | + sound = document.getElementById("sound"); |
| 4 | +(infoText = container.querySelector(".info-text")), |
| 5 | + (removeIcon = container.querySelector(".search span")); |
| 6 | +let audio; |
| 7 | + |
| 8 | +function data(result, word) { |
| 9 | + if (result.title) { |
| 10 | + infoText.innerHTML = `Oops ;) we can't find <span>"${word}"</span>.`; |
| 11 | + } else { |
| 12 | + container.classList.add("active"); |
| 13 | + let definitions = result[0].meanings[0].definitions[0]; |
| 14 | + phontetics = `${result[0].meanings[0].partOfSpeech} /${result[0].phonetics[0].text}/`; |
| 15 | + document.querySelector(".word p").innerText = result[0].word; |
| 16 | + document.querySelector(".word span").innerText = phontetics; |
| 17 | + document.querySelector(".meaning span").innerText = definitions.definition; |
| 18 | + audio = new Audio(result[0].phonetics[0].audio); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +function playSound() { |
| 23 | + audio.play(); |
| 24 | +} |
| 25 | + |
| 26 | +function search(word) { |
| 27 | + fetchApi(word); |
| 28 | + searchInput.value = word; |
| 29 | +} |
| 30 | + |
| 31 | +function fetchApi(word) { |
| 32 | + container.classList.remove("active"); |
| 33 | + infoText.innerHTML = `Searching :) `; |
| 34 | + let url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`; |
| 35 | + fetch(url) |
| 36 | + .then((response) => response.json()) |
| 37 | + .then((result) => data(result, word)) |
| 38 | + .catch(() => { |
| 39 | + infoText.innerHTML = `Oops ;) we can't find <span>"${word}"</span>.`; |
| 40 | + }); |
| 41 | +} |
| 42 | + |
| 43 | +searchInput.addEventListener("keyup", (e) => { |
| 44 | + let word = e.target.value.replace(/\s+/g, " "); |
| 45 | + if (e.key == "Enter" && word) { |
| 46 | + fetchApi(word); |
| 47 | + } |
| 48 | +}); |
| 49 | + |
| 50 | +removeIcon.addEventListener("click", () => { |
| 51 | + searchInput.value = ""; |
| 52 | + searchInput.focus(); |
| 53 | + container.classList.remove("active"); |
| 54 | + infoText.style.color = "#9A9A9A"; |
| 55 | +}); |
0 commit comments