gammatools/web/encounter.js

51 lines
1.7 KiB
JavaScript

document.getElementById('terrainForm').addEventListener('submit', function (event) {
event.preventDefault();
var terrain = document.getElementById('terrainType').value;
// 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('https://gammaworld.gmgauthier.com/roll/encounter', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
terrain: terrain,
}),
})
.then((response) => {
if (!response.ok) {
throw response;
}
return response.json(); // we only get here if there is no error
})
.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';
};
})
.catch((err) => {
err.text().then((errorMessage) => {
imgElement.src = './img/404.jpg';
});
});
});