Sitepoint Book: jQuery Nov to Ninja 2 - jCrop code not working?

Hi all,

I am working through the 2nd edition of the jQuery Novice to Ninja book and the jCrop code doesn’t seem to work, specifically the second part where we are trying to alert the coordinates.

The specific part is chapter 4 - 03 - jcrop.

With the second part of the code, all I get is a small black square box, the image is collapsed? And can’t select and perform the crop to receive the coordinates.

I have downloaded the code archive from the Sitepoint website and am seeing the same thing, no image.

The code I am using is as follows:


<div id="imageCrop">
	<img src="img/lightbox/deliverus2large.jpg" alt="" id="crop" />
	<input type="button" value="Perform the crop!" />
</div><!--/ crop-->


var jcrop = $.Jcrop('#crop',{
	setSelect: [10,10,300,350],
	minSize: [50,50],
	onChange: function(coords) {
		// use the coordinates
	},
	onSelect: function(coords) { // Will only fire when the selection has been defined - when the user has stopped dragging
		// use the coordinates
	}
});

$('#imageCrop :button').click(function(){
        var selection = jcrop.tellSelect(); // tellSelect obtains the current selection - has same properties as the event coordinates
	alert('selected size: ' + selection.w + 'x' + selection.h); // We aren't sending to the server - so we will just alert instead
})

Is there something I am doing wrong?

Many thanks
Simon

The wrong jQuery wrapper is being used.

According to the Jcrop API documentation, the way that the book accesses the Jcrop API must be from the window load event, otherwise unexpected behaviour may (and does) occur:


$(window).load(function() {
    var jcrop = $.Jcrop('#mofat', {
        ...
    });
    ...
});

With more recent versions of Jcrop, from v0.9.9 onwards, the advised way is to use the ready callback instead and set the variable from within the callback function:


$(document).ready(function () {
    var jcrop;
    $('#mofat').Jcrop({
        ...
    }, function() {
        jcrop = this;
    });
    ...
});