javascriptjqueryjquery-webcam-plugin

Javascript functions executes on second time


I am using the jQuery webcam plugin to capture an image from the webcam. I have all script files in order. This button is used to make the capture() call to get the webcam's snapshot:

<input id="capture" type="submit" value="Capture my shot!" onclick="webcam.capture();" />

The webcam is called through the following function:

$("#cam-space").webcam({
    width: 560,
    height: 420,
    mode: "save",
    swffile: "javascript/jscam.swf",
    onTick: function (remain) {
        if (0 == remain) {
            jQuery("#timer-status").text("Cheese!");
        } else {
            jQuery("#timer-status").text(remain + " seconds remaining...");
        }
    },
    onSave: function () {
    },
    onCapture: function () {
        webcam.save("/capture/image");
    },
    debug: function () { },
    onLoad: function () { }
});

My problem is that when I clicked the button the first time, I'm getting the following error in Chrome's debugger:

Uncaught TypeError: undefined is not a function (onclick)

But when I click it the second time, it works and takes the snapshot. What may be the problems?


Solution

  • The function webcam.capture() won't be defined until the Webcam plugin finishes loading. Instead of using an onclick attribute on the button, you should bind the event listener after the plugin is loaded:

    $("#cam-space").webcam({
        /* ... */
        onLoad: function() {
            $("#capture").on("click", webcam.capture);
        }
        /* ... */
    });
    

    Additionally, as Mritunjay suggested in the comments, make sure your $("#cam-space").webcam() statement is contained in $(document).ready(function() { });.