2

I have images in a folder on my server that has all 50 states as the names of each image (nevada.jpg, utah.jpg etc). My tracking software passes State location, and we use the JS code below to show visitors the correct state image based on their location. My problem is, if or any reason we can't pull their location, or they are outside the states, we'd like to have a default image

I've tried just adding a default image in the src but that didn't work.

<a href="http://google.com"><img id="state" src="index_files/deault.jpg" height=300 width=250 class="content-img img-responsive"></a>
      <script>
    document.getElementById("state").src = "index_files/" + getURLParameter("region") + ".jpg";
</script>        

I just need the default image to appear, when no other image is available based on the region parameter

1
  • Well, no, it's not going to work because you're changing the image's source unconditionally. Your question posits "if the user's location is not known, use the default". Where is that IF condition in your code? Commented Aug 20, 2019 at 19:50

3 Answers 3

2

No matter what, the image src gets overwritten. If you'd like to have a backup value, you can notate that like so:

document.getElementById("state").src = 
  "index_files/" 
  + (getURLParameter("region") || "default") 
  + ".jpg";  

Or, better yet:

document.getElementById("state").src = 
  `index_files/${getURLParameter("region") || "default"}.jpg`;
Sign up to request clarification or add additional context in comments.

Comments

1

if an image cannot be loaded, the onerror attribute will be called

<img onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';" id="state" src="index_files/deault.jpg" height=300 width=250 class="content-img img-responsive"></a>

Comments

0

Looks like you need to do a simple data check on the return of getURLParameter().

If getURLParameter() is a custom function, code it so that it returns false if region cannot be found.

Then call the function and set its return to a variable. Then check the variable with a conditional to handle the two possible results:

function getURLParameter(region: string) {
   ...
   if(the region is defined, or able to be fetched) {
      // return the file name
   } else {
      return false;
   }
}

var stateName = getURLParameter("region");

if(stateName){
   document.getElementById("state").src = "index_files/" + stateName + ".jpg";
} else {
   document.getElementById("state").src = "index_files/default.jpg";
}

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.