I have the following code which loads in a URL based on the id of a user-clicked button. I'm looking to compress it down as much as possible, and make it more modular and reusable:
<!-- Function to load in info from different docs -->
function loadDoc(UrlString) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("storybox").innerHTML = xhttp.responseText;
}
};
console.log("URL = " + UrlString);
xhttp.open("GET", UrlString, true);
xhttp.send();
}
function buttonClicked(buttonid) {
console.log("entered case statement");
var UrlString = "templates/story/pt1/Start.html";
switch(buttonid) {
case "YesStart":
UrlString = "templates/story/pt1/YesStart.html";
console.log("test");
loadDoc(UrlString);
break;
case "Sleep":
UrlString = "templates/story/pt1/Sleep.html";
loadDoc(UrlString);
break;
case "Swindon":
UrlString = "templates/story/pt1/Swindon.html";
loadDoc(UrlString);
break;
default:
document.getElementById("storybox").innerHTML = "<p>That part of the story hasn't been written yet. Click to</p><button type='button' class='btn btn-danger' id='nobtn' onclick='buttonClicked('YesStart')'>Restart</button>";
<!-- Output error info -->
console.log(buttonid);
};
};
The case
statement actually goes on a lot longer but I've cut it down. What I want to do is to shorten this code down as much as possible, so it dynamically creates URLs based on buttonid
. Does anyone have an ideas about the best way to do this?