Back to Top

Resolved – Jcrop set width & height as preview image container

Updated 14 July 2016

set jcrop width  height as preview image container

Final Result :

rsz_1screenshot_from_2016-07-13_135503

 

How to do it —

Start your headless eCommerce
now.
Find out More

rsz_1screenshot_from_2016-07-13_135439

Avoid assigning any width height to the image used for jcrop. This sometimes may cause chrome to misplace the jcrop container.

<div id="image_prev_container">
  <img src="#" alt="" id="image_prev">
</div>
<input type="file" id="my_file" accept="image/*">

Apply Jcrop on the selected file

$(function(){
  $('#my_file').on('change', function() {
    var file_name = $(this).val();
    if(file_name.length > 0) {
      addJcrop(this);
  });
  var addJcrop = function(input) {
    if ($('#image_prev').data('Jcrop')) {
      // if need destroy jcrop or its created dom element here
      $('#image_prev').data('Jcrop').destroy();
    }
    
    // this will add the src in image_prev as uploaded
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        $("#image_prev").attr('src', e.target.result);
        var box_width = $('#image_prev_container').width();
        $('#image_prev').Jcrop({
          setSelect: [0, 0, 500],
    	  minSize: [80, 320],
          aspectRatio: 4/1,
          onSelect: getCoordinates,
          onChange: getCoordinates,
          keySupport: false,
          boxWidth: box_width
         });
      }
      reader.readAsDataURL(input.files[0]);
    }
  }
  var getCoordinates = function(c){
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);
  };
});

In chrome or IE change function fired only if the file you selected is different. You may add the below code if need to crop the same file again

$('#seller_banner').on('click', function() {
  $(this).val("");
});

Note: If you are going to get width of child as “$(‘.parent .child’).width();” please prefer to use “$(‘.parent’).find(‘.child’).width()” instead.

View Demo Here         cheer… 🙂

rsz_1screenshot_from_2016-07-13_135503

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home