0

My code is dynamically inserting an img tag into a div on a page.

I am using the Cropper plugin to try to crop this image. The plugin itself doesn't matter that much - I could equally use JCrop for example.

To use Cropper on an image that is already in the DOM it says do this:

HTML:

<div id="files">
 <img src="path/to/img" />
</div>

JS:

$("#files > img").cropper({
  autoCropArea: 0.6, // Center 60%
});

That's fine when the image already exists in the #files div. But I am adding the image dynamically using ajax() calls to my server. I understand I need to delegate but I don't understand how to delegate an entire plugin?

I assumed something like this:

$(document).on("change", "#files > img", function(){
$(this).cropper({
      autoCropArea: 0.6, // Center 60%
    });
});

But it doesn't seem to be working. Any ideas?

volume one
  • 6,800
  • 13
  • 67
  • 146
  • Reinitialize plugin in ajax success callback. FYI, the event you were looking for is called mutation observer but usually shouldn't be used because of some browser performance issue and bad support. Still for information purpose, here is a CSS hack for old (now deprecated) DOMNodeInserted event: http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/ – A. Wolff Jan 26 '15 at 15:46
  • Could you give me an example of how to reinitialize the plugin in the success? In my previous question here http://stackoverflow.com/questions/28151490/how-to-update-dom-with-html-returned-from-server-after-jquery-file-upload-is-don I'm using the `done` function which is the equivalent of ajax() success. – volume one Jan 26 '15 at 15:54
  • right after you insert them in your `done`. – charlietfl Jan 26 '15 at 15:55
  • I'd try: `$('#files').append($(data).filter('img').cropper({...}).end());` to avoid useless plugin recall on already initialized images. `filter` or `find` depending data structure. UDATE: i see this plugin set some data, you could use: `$('#files').append(data).find('img').filter(function(){ return !$(this).data('cropper');}).cropper({...});` – A. Wolff Jan 26 '15 at 15:56

0 Answers0