September 10, 2011

jQuery CSS3 Rotate (and animate Rotation)

This is for browsers with CSS3 support only! That means Chrome 1+, Firefox 3.5+ and IE9+.

Just put this somewhere after jQuery:
(function($){
 var _e = document.createElement("canvas").width
 $.fn.cssrotate = function(d) {  
    return this.css({
  '-moz-transform':'rotate('+d+'deg)',
  '-webkit-transform':'rotate('+d+'deg)',
  '-o-transform':'rotate('+d+'deg)',
  '-ms-transform':'rotate('+d+'deg)'
 }).prop("rotate", _e ? d : null)
 }; 
 var $_fx_step_default = $.fx.step._default;
 $.fx.step._default = function (fx) {
 if(fx.prop != "rotate")return $_fx_step_default(fx);
 if(typeof fx.elem.rotate == "undefined")fx.start = fx.elem.rotate = 0;
 $(fx.elem).cssrotate(fx.now)
 }; 
})(jQuery);

And then if you want to rotate an object:
$("div").cssrotate(95) // value in degrees

And if you want animation:
$("div").animate({rotate:95},{duration:1000})

BTW if you want to check if an old browser didn't rotate the object; you can do something like this:
if($("div").prop("rotate")==null){
 // Fallback
}

4 comments:

  1. Thank you for this post. But i have a trouble

    And then if you want to rotate an object:
    1
    $("div").cssrotate(95) // value in degrees

    This part is working but

    And if you want animation:
    1
    $("div").animate({rotate:95},{duration:1000})

    This party is not working. i failed with animate.

    ReplyDelete
  2. use instead
    $("div").animate({rotate:95},1000);

    ReplyDelete
  3. Helpful as always. Every post you write produce a massive value to your readers that is the only reason it is so popular and has great authority.School website design uk

    ReplyDelete
  4. I am new to design development an this script article is quite helpful for me, I am looking forward to more updates, thankyou

    ReplyDelete

You can use [CODE][/CODE] to post Javascript code.
You can start a sentence with ">" to make a quotation.