Search code examples
jqueryjcrop

jcrop_api is undefined?


When adding Jcrop to a function in Javascript the jcrop_api variable becomes undefined. I had the plugin working (including the api) when I created the Jcrop on window load using $(document).ready(function() { ... });
The problem is I want the user to have the ability to maintain the aspect ratio or to not simply by checking or unchecking a checkbox. So I have the following:

$(document).ready(function() {
    $('#aspectratio').click(function() {
        alert(jcrop_api);
        if (!$(this).is(':checked')) {
            jcrop_api.setOptions({
                aspectRatio: 0
            });
        } else {
            jcrop_api.setOptions({
                aspectRatio: 31 / 12
            });
        }
    });
}

function stopUpload(success, newfile) {
    $('#target').attr('src', newfile);
    $('#preview').attr('src', newfile);
    $('#myfile').val('');
    $('#options').css('display', 'block');
    $('#target').Jcrop({
        onChange: updatePreview,
        onSelect: updatePreview,
        aspectRatio: 31 / 12
    }, function() {
        // Use the API to get the real image size
        var bounds = this.getBounds();
        boundx = bounds[0];
        boundy = bounds[1];
        // Store the API in the jcrop_api variable
        var jcrop_api = this;
    });
}

I've seen other answers such as calling Jcrop in the following way:

$.Jcrop($('#cropbox_full'));

For some reason when doing this the jcrop box doesn't appear at all. Very odd. So basically, my question, what am I doing wrong, and how can I fix this (in a way similar to above) so I can change the aspectRatio from the click of a checkbox?


Solution

  • Okay so it was simple ... The variable (jcrop_api) was just being set in the function, therefore was not accessible from outside the function. I fixed this by setting it as a global variable. I don't know if this is bad practice or not but if someone has a better solution I'd be happy to hear it.