Croppie.js show zoom slider only after the image is selected

519 Views Asked by At

I am using croppie.js for image cropping and uploading. Currently, the image zoom in-out slider is being shown by default. I want the slider to be visible only when the image is selected. Until the user has selected an image, there is no use for the zoom slider. What change do I need to do in order to make the slider not be visible until image selection?

I have prepared a working snippet below to make it easy for debugging.

var resize = $('#uploadContainer').croppie({
  enableExif: true,
  enableOrientation: true,
  viewport: {
    width: 100,
    height: 100,
  },
  boundary: {
    width: 100,
    height: 100,
  }
});

$('#image').on('change', function() {
  var reader = new FileReader();
    reader.onload = function(e) {
      resize.croppie('bind', {
        url: e.target.result
      }).then(function(){});
    }
    reader.readAsDataURL(this.files[0]);
});

$('.btn-upload-image').click(function() {
  resize.croppie('result', {
    type: "canvas",
    size: "original",
    format: "jpeg",
    quality: 1
  }).then(function(img) {
    var imgval = $('#image').val();
    var dataString = {
      image: img,
      imgval: imgval
    };
    $.ajax({
      // AJAX GOES HERE
    });
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>

<div id="uploadContainer"></div>
<label class="file mt-3 text-start">
  <input type="file" id="image" accept="image/*">
  <span class="file-custom"></span>
</label>

1

There are 1 best solutions below

0
Shreyansh Kashyap On

Ah! Minutes after posting the question I figured a custom solution. This was easy. I wanted to delete the question to not look stupid for posting a problem with such an easy solution but then I had a thought to answer it to help other devs who "might" be looking for the same solution.

Solution:

The slider is under a wrapper be default which we need to hide first by css.

.cr-slider-wrap {
  display: none;
}

Now, on change of image simply need to use the .show() or .fadeIn() to display it again.

$('#image').on('change', function() {
  $('.cr-slider-wrap').fadeIn(); // image load

  // REST OF THE CODE GOES HERE (please see question for reference)
});

That's it. Same way you can hide or disable the submit button to end enable or show it back depending upon your choice when the image is selected.