Ideas for dynamically switching an image upon onclick?

On a page containing an image (of artwork), the user can click the image repeatedly to cycle through different variants of that image (which are in an S3 bucket). On a previous (non-Django/Python) version, I did this with a javascript function that changed the url in the DOM… very simple. But in the new Django/Python version, it generates a CORS error, which I have not been able to suppress despite much research. I also tried an all-Python hack which is idiotically complicated and I don’t want it.

So does anyone know of a straightforward way to do this?

I think we’d need to see more details here about your project, how its deployed, the JavaScript that you’re using, whether it’s being loaded from your site or externally, how it’s trying to get the next url, how you’re managing access to that bucket, and anything else that’s a part of this to try and diagnose the root cause of the error.

The web site is hosted on Heroku, and the images are stored in an S3 bucket.

Here’s the HTML that displays the image and handles the onclick:

<img id="mainImage" class="detail_image" src="{{EXTERNAL_IMAGES_URL}}full/{{artwork.image_name}}" onclick="switchImage()" style="cursor: zoom-in"/>

EXTERNAL_IMAGES_URL is the name of the S3 bucket. So for example, the above might reference the URL “https://myBucketName.s3.amazonaws.com/public/images/small/myImageFileName.jpg”. This works fine.

When the image is clicked, the JS function switchImage() changes the 5th element (e.g. from “small” to “large”) in that URL, so using the above example, the result might be “https://myBucketName.s3.amazonaws.com/public/images/large/myImageFileName.jpg”.

… and then checks to see if that file actually exists; if not, it tries another variant (e.g. small > large > detail > small…):

function doesFileExist(urlToFile) {
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send(); ///////////////// generates CORS error
    return xhr.status == "200" // exists
}

The xhr.send() function fails with:

XMLHttpRequest cannot load <the url> due to access control checks.

It does not fail if I’ve suppressed the error in my browser (Safari), in which case the script goes on to update the URL in the DOM, and the new image variant is displayed.

document.getElementById("mainImage").src = new_url;