I am trying to validate an image URL if it exists or not using JavaScript. Basically I want to assign the URL to image if its valid. But the JavaScript function which validates the URL, as not executing line-by-line, disrupts the logic and returns all URLs to be true. Is there any way I can hold the control inside the urlExists
function till all its threads are completed?
Currently the control do not wait for the result of error message and jumps over it to back to the calling function with true value always. Any idea how can I make the function hold control here?
function urlExists(testUrl) {
var ret = true;
var newImage = new Image();
newImage.src = testUrl;
$(newImage).error(
function(){
ret = false;
}
);
return ret;
}
function changeImagePath(obj){
var oldUrl = obj.src;
var newUrl = oldUrl.replace("abc","xyz");
if(urlExists(newUrl)){
obj.src = newUrl;
}
}
<img src="http://sample.com/images/srpr/logo_abc.png" onclick="changeImagePath(this)" />
Also meant to mention I am dealing with cross-domain image URLs.