0

I have a webcam that overwrites "pic.jpg" every few second. The problem I'm having is sometimes my code below executes in the exact time that the webcam is overwriting the old image, resulting in a broken image. Then when the function runs again (after the webcam has finished uploading the image) everything works fine and the image shows up. So I'm trying to stop the broken image from ever showing. I'm new to javascript/jquery, so this may be wrong on many levels:

<style type="text/css">
#pictest {display:none}
</style>

function updateCams(){
    var camurl = "/pic.jpg?"+new Date().getTime();
    $("#pictest").attr("src", camurl);
    $("#pictest").error(function(){
        /* image was being written. Restart the function and try again */
        updateCams;
    })
    /* I want a success/valid type function to go here and update the visible image only on success*/
    $("#pictest").valid(function(){
        $("#pic").attr("src", camurl);
    })
};
setInterval( "updateCams()", 2000 );

<img src="pic.jpg" width="640" height="480" id="pic" alt="Loading..." />
<img src="pic.jpg" id="pictest" />

Anyway, the "valid" function doesn't work. I've tried valid/validate/success and even an if/else, but only .error works right.

Brandon
  • 57
  • 1
  • 9
  • 1
    Have you seen this [answer](http://stackoverflow.com/a/9589845/1408356)? – Scrimothy Oct 02 '12 at 20:28
  • 1
    Use the load event, and don't set the `src` until after you have bound `.error` and `.load` – Kevin B Oct 02 '12 at 20:29
  • Not sure I get this, but did you try this -> [FIDDLE](http://jsfiddle.net/hXKNJ/) ??? And don't eval in you're interval! – adeneo Oct 02 '12 at 20:37
  • The problem isn't that the image hasn't finished loading, it's that the image was being uploading when grabbed, so its 'corrupt'. Outside of using plugins, I'm screwed? There is no way to do add a function like the .error function, only the opposite? Or even an "else" statement if there is an error? – Brandon Oct 02 '12 at 21:25

1 Answers1

1

UPDATE

You should use a plugin such as this one: https://github.com/desandro/imagesloaded

It will properly detect that the image source is loaded and give you the functionality you desire.

BELOW IS INCORRECT

Look at this post for the answer: jQuery callback on img src replacement?

Essentially, you can use a load event listener for the element.

$('#imageID').load(function() { .... });

NOTE: Just keep in mind that load() doesn't always fire when the image is in the browser cache. You need to add some logic using the DOM img.complete. Read the comments on load() documentation page for some insight. (via @MPD).

Community
  • 1
  • 1
seangates
  • 1,396
  • 10
  • 28
  • If you bind the events before you set the source, the events will always fire appropriately regardless of cache. – Kevin B Oct 02 '12 at 20:34