const searchForm = document.querySelector(".search-form"); const result = document.querySelector(".result"); const submitButton = document.querySelector(".submit-button"); const clearDiv = () => { result.innerHTML = ""; }; const buttonLoading = () => { submitButton.innerHTML = "loading..."; submitButton.setAttribute("disabled", true); }; const buttonDefault = () => { submitButton.innerHTML = "Submit"; submitButton.removeAttribute("disabled"); }; const renderImg = (imageName) => { clearDiv(); const img = document.createElement("img"); img.src = `/images/${imageName}`; result.appendChild(img); }; const getResult = async (searchQuery) => { const response = await fetch(`search?query=${searchQuery}`); const json = await response.json(); return json.result; }; searchForm.addEventListener("submit", async (event) => { event.preventDefault(); const query = document.querySelector("#query"); buttonLoading(); try { const res = await getResult(query.value); renderImg(res); } catch (err) { console.error(err); clearDiv(); } finally { buttonDefault(); } });