gammatools/web/encounter.js

46 lines
1.6 KiB
JavaScript
Raw Normal View History

document.getElementById('terrainForm').addEventListener('submit', function (event) {
2024-06-26 07:45:20 +00:00
event.preventDefault();
var terrain = document.getElementById('terrainType').value;
const queryParams = new URLSearchParams({
terrain: terrain,
});
2024-06-26 07:45:20 +00:00
// Insert the loading.gif before making the fetch request
let resultSection = document.getElementById('resultSection');
resultSection.innerHTML = '';
let imgElement = document.createElement('img');
imgElement.src = 'img/checking.gif';
imgElement.style.width = '500px';
imgElement.style.height = '500px';
imgElement.style.display = 'block';
imgElement.style.marginLeft = 'auto';
imgElement.style.marginRight = 'auto';
resultSection.appendChild(imgElement);
fetch(`${window.BASE_URL}/gameplay/encounter?${queryParams}`)
.then((response) => {
if (!response.ok) {
throw response;
}
return response.json(); // we only get here if there is no error
2024-06-26 07:45:20 +00:00
})
.then((json) => {
// Handle null encounter
let encounterText = json.encounter ? json.encounter : 'No Encounter';
// Change the src attribute of the image after fetch resolves
setTimeout(() => {
imgElement.src = './img/' + encounterText + ".jpg";
}, 1000);
imgElement.onerror = function () {
this.onerror = null;
this.src = './img/404.jpg';
};
2024-06-26 07:45:20 +00:00
})
.catch((err) => {
err.text().then((errorMessage) => {
imgElement.src = './img/404.jpg';
});
});
2024-06-26 07:45:20 +00:00
});