I have a folder that contains one image of each of the 50 states. Some are PNG and the others are JPG files. The name of each file is simply the state name and the extension is either PNG or JPG. "Alabama.jpg" "Connecticut.png" etc...
A variable called stripState is also simply the name of each state which correlates exactly to the image file names.
I can call and produce the appropriate image using the following code for the JPGs:
stateImageDisplay.src = `state-pics-converted/${stripState.state}.jpg`;
and the following for the PNG files:
stateImageDisplay.src = `state-pics-converted/${stripState.state}.png`;
This works only when using either one or the other. All the JPGs will display appropriately or all the PNGs.
I know that I could convert all of the files within the folder to either JPG or PNG but I would like to know how to use JavaScript to choose between whichever file is available.
I want to write a code that calls whichever image file matches the "stripState"...be it a JPG or PNG. If the "stripState" is "Kentucky", the javaScript makes the "stateImageDisplay.src" equal either "Kentucky.jpg" or "Kentucky.png"...whichever one exists.
I thought maybe I could use an "if statement" to check if one of the two filetypes is found. If so, use that one, if not, use the other type. Like below:
if (`state-pics-converted/${stripState.state}.jpg` === undefined) {
stateImageDisplay.src = `state-pics-converted/${stripState.state}.png`;
} else {
stateImageDisplay.src = `state-pics-converted/${stripState.state}.jpg`;
}
I have also tried swapping "undefined" for "onerror" but had no success.
The console log error shows the message "net::ERR_FILE_NOT_FOUND" when the "sought for" file extension is unavailable. I don't know what the equivalent to that would be in order to use it in the if statement...
Any suggestions? Thanks in advance