Skip to content
Advertisement

JS style-changes don’t get applied when inside request

I want to make it such that an image on a website gets its “onclick” event disabled and a gray filter applied, if a certain file on the same domain is not found. I want to use purely JS and have tried this so far:

function fileNonExist(url, callback){
        var http = new XMLHttpRequest();
        http.onreadystatechange = function() {
                if (http.readyState === XMLHttpRequest.DONE && callback) {
                        if(http.status != 200){
                                callback();
                        }
                }

        }
        http.open('HEAD', url);
        http.send();
}

fileNonExist("theFileIAmLookingFor.html", () => {
        console.log("image changed");
        image.onclick = "";
        image.style.filter = "grayscale(100%)";
});

I have the image initialized and displayed. Thus image.onclick = "" and image.style.filter = "grayscale(100%) both work, if they are used normally. However, even though the function blocks are executed as intended (Console logs “image changed” if the file isnt found, and nothing otherwise.) none of the style changes are ever visible, if they are executed from within those blocks. Why might that be and how could I fix it?

Advertisement

Answer

I found out the solution myself, while talking to Emiel Zuurbier: I noticed that the code works if I open the html file normally in my browser. The bug occurs, if I access the file over a webserver, which i’ve done the whole time. If I shut down the server while the site is still opened in the browser, then the changes also get applied. If I look at the requests with dev tools in the browser. I see that only the successfull requests are finishing and the unsuccessfull ones are left pending forever. Thats why the changes get applied when the server is shut down and all pending requests get closed with errors. The Server uses the Node.js “fs” module and its readFile method.

I will now try to turn the styles around so all images start off gray and without “onclick” – methods and only become unlocked once the file is found. This way the images with pending requests remain gray.

Advertisement