0

Here is the fiddle- http://jsfiddle.net/gfWES/59/

When background-image will point to the location where it would not find a image, I want to show an alternate image which is located at below location- http://fancyapps.com/fancybox/demo/1_b.jpg

Ultimately, I have to achieve the above in knockout.

<td class="cell">
<div class="contact-photo" data-bind="click: $parent.onAlertClick, style: { backgroundImage:     $parent.photoUrl($data) }, css: { 'has-notifications': $parent.showAlert($data)}, onerror:alert('error')"></div>
</td>

In above code- if "$parent.photoUrl($data)" points to a url where image doesn't exist, I want to point "backgroundImage:" to some other location to show any alternate image.

Peeyush
  • 95
  • 8

1 Answers1

1

The only way of checking if an image exists is to request it. Using jQuery you'd do a $.ajax({url:'somefile.png', type:'HEAD', error:image_does_not_exist}); where image_does_not_exist is a callback function. Then you'd set the value returned by photoUrl to the default one.

Sergiu Paraschiv
  • 9,929
  • 5
  • 36
  • 47
  • Thanks for your answer.!! But, what if it turns out to be a cross browser request which is not allowed straight away. – Peeyush Jan 07 '15 at 12:20
  • Then it's not possible. You need proper CORS headers on the response. _But_ a good alternative (that does not require CORS) is to use an `img` and listen to `onLoad` on it as described in the answer here: http://stackoverflow.com/questions/9809015/image-onerror-event-never-fires-but-image-isnt-valid-data-need-a-work-around – Sergiu Paraschiv Jan 07 '15 at 13:29