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 = [

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}`;


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