Rotate and Fly off elements with jQuery and CSS3

In this post, we will look at how we can use CSS3’s property transform and other vendor-specific properties to rotate elements and finally fly them off the page with jQuery. We will also use setInterval function of javascript for the continuous animation or rotation of the elements. So let’s get started with it.

Rotating Elements

To transform/rotate elements, there is a CSS3 property transform, here is the syntax of it:

transform: rotate(Xdeg)

Where X can be any number denoting the amount of rotation/angle. For example:

transform: rotate(90deg)

Any element applied above rule, will transform to 90 degrees.

Continuous Rotation

To rotate elements continuously, we can use the setInterval function of javascript along with some math. Check out the demo below:

Rotating Elements with jQuery & CSS3

The code of interest for the rotation is as follows:

$('.rotate').click(function(){
	var interval = null;
	var counter = 0;
	var $this = $(this);
	clearInterval(interval);

	interval = setInterval(function(){
		if (counter != -360) {
			counter -= 1;
			$this.css({
				MozTransform: 'rotate(-' + -counter + 'deg)',
				WebkitTransform: 'rotate(' + -counter + 'deg)',
				transform: 'rotate(' + -counter + 'deg)'
			});
		}
	}, 10);
});

Here I assume you know the basics of jQuery like ready handler, class and id selectors, etc. I have explained those things in my other posts, so I won’t be discussing them but instead I will concentrate on the part of the code which is responsible for the rotation.

First of all, we assign a click handler to each element with the class of rotate. Later we create the necessary variables including $this equalized to $(this) meaning the current clicked element, this is useful because we will reference this variable later in the setInterval function. As an element gets clicked, we also stop the current animation or clear the time interval using clearInterval function.

Later inside setInterval function, we decrement the variable counter by one with each 10th Milli-second passed (the second argument specified to the setInterval function). I have specified lesser time so that animation is little faster. The reason why I decrement the value of counter is that I wanted to rotate the elements in anti-clock-wise direction. This variable keeps on decreasing until it reaches -360 specified above in the if condition meaning that our element has rotated completely and has come back to its original place.

Now since we have put transform CSS3 property in the setInterval function and $this refers to current clicked element, the element starts rotating with continuous animation because counter variable has been specified as the degree of rotation:

transform: 'rotate(' + -counter + 'deg)'

Note that MozTransform and WebkitTransform are vendor-specfic CSS3 properties of Mozilla and Webkit (Chrome and Safari) browsers.

I have also created javascript version of rotating elements which can be seen here:

Rotating Elements with JavaScript & CSS3

So that is all there to rotating the elements in continuous fashion. Next we will see how with slight modification we can fly the elements off the page.

Flying Elements Off the Page

To fly elements off the page, we use jQuery’s animate method like this:

animate({left: '+=' + counter + 'px'}, 40);

That one single line is needed to fly off elements off the page, we add this line to our previous code just after we applied CSS3 properties like this:

$('.rotate').click(function(){
	var interval = null;
	var counter = 0;
	var $this = $(this);
	clearInterval(interval);

	interval = setInterval(function(){
		if (counter != -360) {
			counter -= 1;
			$this.css({
				MozTransform: 'rotate(-' + -counter + 'deg)',
				WebkitTransform: 'rotate(' + -counter + 'deg)',
				transform: 'rotate(' + -counter + 'deg)'
			}).animate({left: '+=' + counter + 'px'}, 40);
		}
	}, 10);
});

It is time to check out the demo:

Fly Off Elements with jQuery & CSS3

Here, we have basically specified left property of CSS to the animate method so that elements flies away to the left. You could also specify top to fly elements away to to the top. In fact, you could specify many other CSS properties to animate method such as width, height, margin, etc. Generally, you can specify any CSS property to animate method that can be specified in pixels values or in other words that could be increased or decreased.

Now that we have seen how to rotate elements and fly them off, it is up to you how you can take the idea and use in your cases. I suspect there could be  quite some ways we can use this technique effectively. I might come up with something fancy in my future posts while using this technique. As a last example, here is one idea to delete elements while flying them off the page:

Deleting Elements while Flying them off the Page

Browser Compatibility

The transform property works in all modern and standard-compliant browsers. It does not however work in IE, however there exist alternative when it comes to IE which is using IE-specific transformation filters you might want to consider for the rotation purpose. Here is IE-specific example:

#myElement {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
}

The value for the rotation can be either 1, 2, 3, or 4. Those numbers represent 90, 180, 270, or 360 degrees of rotation respectively.

There also exists cssSandpaper, the CSS3 Javascript library comes in handy when you want transformations to work across all browsers.

I hope you came to know about something useful you can put to use in your own ways.

Custom Facebook Connect Image

One of the ways you can put facebook connect button on your site is to use <fb:login-button> fbml tag something like this:

  <fb:login-button onlogin="window.location='www.example.com'"></fb:login-button>

That will show default facebook button with a rather small image. You can make the button little larger by specifying length and size attributes like this:

  <fb:login-button onlogin="window.location='www.example.com'" length="long" size="large"></fb:login-button>

However, the requirement in my case was that the button should be even bigger. I searched through the facebook connect docs and elsewhere but did not find a way to customize the facebook connect image (it is rendered directly by facebook; let me know if there is a way via comments please). I thought why I can’t force the facebook connect button to use the image that I specify. I fired up firebug (the addon of firefox) and this is what it showed for the <fb:login-button> fbml tag:

As can be seen, facebook automatically applies FB_login_button class amongst others to the connect button. As you can see, there is an img tag inside, that was all I needed to get my own image for the connect button. The idea is to find the image inside connect button and replace with your own once DOM has loaded. Now you get the idea, I wrote this jQuery code to get custom image for the connect button:

<script type="text/javascript">
$(function(){
  // overwrite the fb connect image - let's force it !!
  $('.FB_login_button').find('img').attr('src', 'img/my-custom-image.png');
});
</script>

We use the selector .FB_login_button and then use find method to find the image inside element (<fb:login-button>) having that class and replace its src attribute with the path of our custom image.  Since we have wrapped our code in ready handler $(function(){…}), our code will execute as soon as DOM becomes ready and when you visit the page, it will have your own custom facebook connect button image.

I also noticed that there was a link tag generated with the class of fbconnect_login_button. We could use that just as well like this:

<script type="text/javascript">
$(function(){
  // overwrite the fb connect image - let's force it !!
  $('.fbconnect_login_button').find('img').attr('src', 'img/my-custom-image.png');
});
</script>

Now this is good as long as you are using jQuery on the page where facebook connect button exists. But if you are not using jQuery, you can do the same thing with vanilla javascript albeit with little more code. Here is how you can do the same thing with vanilla javascript:

<script type="text/javascript">
window.onload = function(){
  var ourImg = null; // this will store the facebook connect img tag

  // find all the links on the current page
  var links = document.getElementsByTagName('a');

  // loop over all the links
  for(var i = 0; i < links.length; i++){
    // get class of this link
    var cls = links[i].className;

    // check to see if this is the link with specified class
    if (cls === 'fbconnect_login_button'){
      ourImg = links[i].firstChild; // which is img tag we need
      break;  // done, let's get the hell out of here
    }
  }

  // finally replace with our own image !
  ourImg.src = '<?php echo base_url() ?>images/fb.png';
};
</script>

Ops ! that is a lot of code I have written compared to jQuery’s but that’s what you need if you are not using jQuery on your page. Note that this time, we are using load event of the window window.onload = function(){…} which will fire when all the page resources are loaded including images, frames and the DOM unlike ready handler of jQuery which fires as soon as DOM becomes ready and runs before images, frames or any other external resources loaded into the page.

Finally, this is the page that now uses custom facebook connect button image while using <fb:login-button> fbml tag:

View the Page