Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Jcrop and IE and dynamically added image

I'm adding an image to the page and then using JCrop on it, but it doesn't seem to work in IE8 unless I wait a bit between $img.show() and the invocation of the JCrop method. Here is a minimal example where JCrop works also in IE8, but I would like to get rid of lines 16 and 18 or at least understand what needs to happen within those 250 milliseconds.

 10       var $img = $('<img id="example" style="display:none;">');
 11 
 12       $("body").append($img);
 13 
 14       $img.on("load", function () {
 15           $img.show();
 16           setTimeout(function () {
 17               $("#example").Jcrop();
 18           }, 250);
 19       });
 20 
 21       $img.attr("src", "/assets/example.png");
like image 393
nicolagi Avatar asked Feb 03 '26 22:02

nicolagi


1 Answers

As with the script element, IE8 and under fire legacy readyStateChange events rather than standard load events for image src updates, so the timer is masking the fact that the event is not recognized. The solution is to fork the code before the callback:

function imageSwap()
  {
  var $img = $('<img id="example" style="display:none;">');

  $("body").append($img);

  $img.attr("src", "/assets/example.png");

  if(!!document.addEventListener)
    {
    $img.on("load", loadTest)
    }

  else
    {
    $img.get(0).attachEvent("onreadystatechange", loadTest);
    } 

  function loadTest(event)
    {
    $img.show();
    $("#example").Jcrop();
    }
  }
like image 94
Paul Sweatte Avatar answered Feb 06 '26 10:02

Paul Sweatte