Search code examples
jqueryjcrop

Jcrop not working properly on modal window


I have a wrapper div box that is the modal window. There is an image inside the modal window. When Jcrop() is added to this image, I get an unintended result. As shown below:

enter image description here

enter image description here

Notice that the image appears inside the modal window and outside. This is the jQuery code used:

$("#previewSub").Jcrop();  //previewSub is the smaller preview

How can I get around this issue? I tried removing the Jcrop from the picture when the modal is closed but I still get the same result.

Here's a fiddle that demonstrates my issue:

https://jsfiddle.net/d562yrsp/1/


Solution

  • To get the effect you want, change your HTML to this:

    <div id="modal">
      <div class="preview-container">
        <img id="previewSub" src="http://www.cuteadorable.com/wp-content/uploads/2015/05/cuteadorable-kitty.jpg" />
      </div>
    </div>
    <button id="abutton">
      show modal
    </button>
    

    Change your CSS to this:

    #modal {
      position: absolute;
      background: black;
      width: 300px;
      height: 300px;
      display: none;
    }
    .preview-container {
      top: 100px;
      left: 80px;
      width: 150px;
      height: auto;
      background-color: #2185C5;
      position: relative;
    }
    #previewSub {
      width: 150px;
      height: auto;/* use auto here so it doesnt distort the aspect ratio of the image */
    }
    #abutton {
      position: absolute;
      background: red;
      top: 350px;
    }
    

    And change your jQuery to this:

    $('#abutton').on("click", function() {
      $("#modal").show();
      $('#previewSub').Jcrop();
    });
    

    Here is an updated jsFiddle

    Note that Jcrop sets the below styling in the target image:

    style="display: block; visibility: visible; width: 150px; height: 84px; border: none; margin: 0px; padding: 0px; position: absolute; top: 0px; left: 0px; opacity: 1;"

    This overrides the position, top, and left settings your were adding in the rule for #previewSub. To avoid this, I have placed the image in a container div with the class preview-container and applied the positioning to that container instead.

    The CSS may need some tweaking for your needs but this should get you sorted.