Skip to content Skip to sidebar Skip to footer

Can I Catch Http Errors When Using JQuery To Modify Styles?

If I use jQuery to set the background image of the page like so: $('body').css({ 'background-image': 'url(' + myImageUrl + ')' }); How can I detect and handle HTTP errors (500

Solution 1:

Try this

jQuery

Live Demo

var $image = $("<img />");
$image.on("error",function() { 
  $('body').css({
    "background-image": 'url(defaultimage.jpg)'
  });
}).on("load",function() {
  $('body').css({
    "background-image": 'url(' + myImageUrl + ')'
  });
}).attr("src",myImageUrl);

JavaScript:

var image = new Image();
image.onerror=function() { 
  document.body.style.backgroundImage="url(defaultimage.jpg)"
}
image.onload=function() {
  document.body.style.backgroundImage="url("+myImageUrl+")"
}
image.src=myImageUrl;

Post a Comment for "Can I Catch Http Errors When Using JQuery To Modify Styles?"