I have a text file that looks like this: sciFi.png, posed.png, birdA.png, dolphin.png, horse.png, shake.png, loft.png, basement.png, avenger.png, friend.png
I'm importing that file to a js doc and attempting to create an array out of that file and then use the forEach() method to create a substr() for each array element to take off the '.png' (so the output would be sciFi, posed, birdA, dolphin and so on).
Here is my code so far:
html
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>My fabulous document</title>
</head>
<body>
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">change content</button>
</div>
</body>
<script type="text/javascript" src="getImgButton.js">
</script>
</html>
js
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
pix = this.responseText;
myPix = pix.split(",");
myPix.forEach(myFunction);
function myFunction(myPix) {
// var buttVal = myPix.substr(0,myPix.indexOf("."));
}
}
};
xhttp.open("GET", "imageList.txt", true);
xhttp.send();
}
I know I'm probably way off but I'm trying to figure out what to put in myFunction() to get this to work. Any suggestions?
Here's a modern way to write this:
async function loadDoc() {
const response = await fetch('imageList.txt');
const body = await response.text();
const images = body.split(',').map(
fileName => fileName.split('.')[0]
);
console.log(images);
}
The errors in your original snippet has to do with how you called forEach:
const images = [];
myPix.forEach(myFunction, function myFunction(item) {
var buttVal = myPix.substr(0,myPix.indexOf("."));
images.push(buttVal);
});