Hello everyone. Any clue why the following JS code isn’t going to work for randomizing the dice image by file name? The image file names are formatted dice1.png, dice2.png, etc, all the way through 6. The initial state of the image source links to dice6.png in my file path and appears correctly in the browser. I’m getting a syntax error saying that the variable randomNumber1 was already declared, but I only see this being done once in my code and I’ve done a hard reload in the browser just in case. The same image is continually shown in the browser upon refreshing, but the intent of the code is to randomize the numbers 1-6 in my file name (using string interpolation) and set that randomized value equal to the image source, thereby updating the image that appears on the page. I am brand new at DOM manipulation, so I would appreciate any input that can be provided.
JS:
let randomNumber1 = Math.floor(Math.random()*6) + 1;
document.querySelector(".dice, .img1").setAttribute("src", `C:...path...images\dice${randomNumber1}.png`);
He is also selecting for two different classes which I do not think works, but I believe that he really only needs to be selecting for the image as is.
Removing the comma does make sense. I didn’t include this initially but a comment in another forum seemed to indicate it should be there. I intended to select the img1 class within the dice class. However, now I am getting Uncaught TypeError: Cannot read property ‘setAttribute’ of null. When I check the getAttribute, I see the full path and the variable properly interpolated into the string text spelling out the path.
If you create a Codepen or Codesandbox with your code we can better help. If you use Codepen you will not be able to use file paths to the images so just use some online image placeholder instead.
Thanks for taking the time. I can’t access the full body of code from my current location, but I can tell you that the script tag is at the bottom of the body. I made sure of that.
As far as I can tell, there is nothing in the current code you have posted that should prevent you from getting the image element or changing the source of it.
I appreciate everyone taking the time. It turns out my file path was referencing the full path (C:\Users...images/dice${}.png), but when I reduced it to simply images/dice${randomNumber1}.png the issue went away. I still haven’t figured out why this is, but I’m going to make note and do some research on linking to local files. Thanks again for everything you did, and thanks lasjorg for making the jsfiddle code for me to compare.