Trying to grab images at random in JavaScript using an array and function which compiles but will at random fail to select the full name of image from array causing no render on html page

As the title says, I’m trying to call an image name from an array and use that to render the image on my front-end. The code compiles properly with no errors in the console except that it can’t find the image because the code randomly only grabs the first few characters of the image title. I can’t seem to identify why. All the array items are in line with the filenames and the locations of all the files are correct. It seems the problem is with the function that grabs the image names and puts them at the end of the document.GetElementById command. If someone could help identify why this wouldn’t work properly, please let me know! I followed a tutorial for the code and adjusted it to work with other aspects of my app, but I’m not a developer or a coding student I just have a basic understanding. Thanks in advanced! Here’s the js for this particular page:

// Image Array

lvl1_vln_image_array = [
‘L1A#3.png’,
‘L1A3.png’,
‘L1Ab3.png’,
‘L1G#3.png’,
‘L1G3.png’,
‘L1B5.png’,
‘L1Bb5.png’,
‘L1A#5.png’,
‘L1A5.png’,
‘L1Ab5.png’,
‘L1G#5.png’,
‘L1G5.png’,
‘L1Gb5.png’,
‘L1F#5.png’,
‘L1F5.png’,
‘L1E5.png’,
‘L1Eb5.png’,
‘L1D#5.png’,
‘L1D5.png’,
‘L1Db5.png’,
‘L1C#5.png’,
‘L1C5.png’,
‘L1B4.png’,
‘L1Bb4.png’,
‘L1A#4.png’,
‘L1A4.png’,
‘L1GAb4.png’,
‘L1G#4.png’,
‘L1Gb4.png’,
‘L1F#4.png’,
‘L1F4.png’,
‘L1E4.png’,
‘L1Eb4.png’,
‘L1D4.png’,
‘L1D#4.png’,
‘L1Db4.png’,
‘L1C#4.png’,
‘L1C4.png’,
‘L1G4.png’,
‘L1C3.png’,
‘L1B3.png’,
‘L1Bb3.png’,
]

function get_random_image() {
// Get Random Index
random_index = Math.floor(Math.random() * lvl1_vln_image_array.length);

// Get an image at the random index

selected_image = lvl1_vln_image_array[random_index];

// Display the image
document.getElementById('image_shower').src = `images/ViolinLevel1/${selected_image}`;
console.log(selected_image);

}

Not sure how to format this on the forum, sorry.

Here’s an example image of how it looks when it tries to grab a name but fails:

Not sure it is a good idea to have special characters in your file names, specifically, the hash sign. #. That symbol when it appears in a URL indicates a page fragment. Rename all the files containing this character and see if that helps.

1 Like

I’ll try this, thanks!

1 Like

This worked perfectly! I was a bit confused because I figured the # was within a string but it seems it still had an effect on it. Thanks so much!

1 Like