Skip to content

Instantly share code, notes, and snippets.

@stephenmckinney
Created April 26, 2012 07:54
Show Gist options
  • Save stephenmckinney/2497307 to your computer and use it in GitHub Desktop.
Save stephenmckinney/2497307 to your computer and use it in GitHub Desktop.
Replace broken images with placehold.it images with JQuery
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("img").error(function(){
$(this).attr("src", function(){
size = ($(this).attr("width") + "x" + $(this).attr("height")).match(/\d+x\d+|\d+/i);
return "http://placehold.it/" + size;
});
});
});
</script>
<figure>
<img src="http://octodex.github.com/images/strongbadtocat.png" width=100 height=100 />
<figcaption>Good image</figcaption>
</figure>
<figure>
<img src="poo" width=100 height=150 />
<figcaption>Bad image</figcaption>
</figure>
<figure>
<img src="poo" width=100 />
<figcaption>Bad image with no width</figcaption>
</figure>
<figure>
<img src="poo" height=100 />
<figcaption>Bad image with no height</figcaption>
</figure>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment