Monday, May 31, 2010

Rotating in jquery (firefox problems)

In my entry on rotating images in jquery/javascript I mentioned I'd not had the problem that the unofficial patch was supposed to fix. Well, now I've seen it even using that patch. The problem is this: if you try to rotate an image (in Firefox, at least) that hasn't fully loaded it all goes wrong.

When rotating in Firefox/Safari you are making a copy of the image; the jquery-rotate patch is to make sure your copy has been properly initialized before doing anything with it. My problem was similar: I was trying to rotate an image that hadn't loaded. (Curiously it didn't happen on a 106Kb image, but did consistently on a 69Kb image; the smaller image was in landscape, while the larger image was portrait, but I have no idea if that is related.)

My rotate call is in a function called init(). I first tried calling init() from the image's onLoad(), which worked most of the time. I also tried a more complex solution that involved not calling init() until both the image's onLoad() and JQuery's $(function(){...}); (what I personally like to call onDomLoaded) had both run. But still it happened on certain images, and I now feel that that level of complexity is not needed (also, onDomLoaded always seems to run before the image's onLoad triggers).

So, my solution is this:
  <img src="test.jpg" id="img"

Using a time-out of 25ms was not enough, but 40ms seems reliable. The downside is that the image flashes on screen briefly in the original orientation before rotate can kick in. We can fix that by having it invisible initially:
  <img src="test.jpg" id="img" style="visibility:hidden"

  function init(){


Unknown said...

Saw the June issue of the British magazine Practical Web Design (.net mag. in the UK) in Kinokuniya Times Square today, and there's an article on doing animation (and the same rotation) using the Processing language.

Unknown said...

The September issue of the British magazine Practical Web Design (.net mag. in the UK) has an article on CSS: "Spice up your CSS" which says that most of the current crop of browsers support cool CSS effects like rotation:
-webkit-transform: rotate(ndeg);
-moz-transform: rotate(ndeg);
-o-transform: rotate(ndeg);
-transform: rotate(ndeg);
where (ndeg) is like (90deg)