Archive for the ‘JavaScript’ Category
Posted on November 18, 2008 - by admin
Create An Analogue Clock with CSS3 and jQuery
Its that time again. Today we are going to show you something sweet. A preview into what the new CSS3 standard can do, namely with tag ‘rotate’. I really started whacking my brain about what you could rotate on a web page. Then it occurred to me. A Clock hand rotates! so lets get started.
CSS3 Transform:rotate
Transform:rotate a brand new feature of CSS3 that will allow you to.. you guessed it! Rotate stuff. It will also be able to scale and skew and tween objects around your web page. All these can be animated with the transition property.
It shares the same principle as the current popular frameworks like jQuery to create animation elements on your page. As with jQuery you can animate pretty much any css property worth doing so with transition.
Thinking of the :hover effect and you should get the relative idea. jQuery or mootools are a lot more powerful but you can still do alot of cool stuff with a lot less download time.
Take NOTE :
When CSS3 is eventualy released ( with HTML5 ) you will be able to view this demo in all the current browsers. Right now, this demo will only work with Google Chrome (windows) or the latest version of Apples Safari browser (mac) as they are the only current browsers that support the transform propery of CSS3 via the -webkit- prefix. FF3 is not to far away either.
Oh and no This will never EVER work with Internet Explorer 6 ( god damn it let a dead dog die already ! )
The Graphics
First youll need the interface for the clock. We have several aspect that we will need, namly the face, and three hands. All the animated parts are sliced in photoshop at 600 px high and 30px wide, are positioned vertically in the upmost center as per default the rotate property ‘ rotates’ from the center of the element. You can use ‘transform-origin’ to set a rotate point if you would like.
The clock is a generic clock, but there is nothing holding you back from creating the micoagelo of clock if it tickles your fanny. The animated parts are all PNG images ( I hate you IE6 ) thrus making this effect possible.
Download the Tutorial files
The HTML Part
The mark-for the clock is a very creative un-ordered list. Each item will contain an animated part and is given the relevant id. Here it is.
<ul id="clock"></ul>
The CSS
#clock { position: relative; width: 600px; height: 600px; margin: 20px auto 0 auto; background: url(clockface.jpg); list-style: none; } #sec, #min, #hour { position: absolute; width: 30px; height: 600px; top: 0px; left: 285px; } #sec { background: url(sechand.png); z-index: 3; } #min { background: url(minhand.png); z-index: 2; } #hour { background: url(hourhand.png); z-index: 1; }
The CSS is really simple too. As the moving parts share the same dimensions and start positions we can declare these together to avoid repeating ourselves making the CSS a bit leaner.
Theis given a position of relative allowing us to absolutely position the clock hands inside it.NOTE: Rotate doesn’t effect layout and the object behaves like an absolutely positioned element outside the normal flow when rotated.
So where is is the CSS3 stuff? Well we’re going to apply that using some simple jQuery.
The jQuery JavaScript
1. Get the timing information for the clock.
2. Calculate and inject the CSS style (rotation angle) for each element.
3. Update the CSS style info at regular intervals.
It should be noted that jQuery has no problem at all using these new CSS3 properties. Also as the styles are allocated dynamically and not from the stylesheet this clock still validates as CSS2.1!
Getting the time
Some of you might (well I did!) equate date and time info with PHP, and when I started this PHP was my first thought, but then I discovered javascript has it’s own built in functionality for getting date and time data too. Note with JavaScript the time is local to the machine not the server.
We’re going to get this info using the Date() syntax and assigning that to a variable. We can get each hands specific data by attaching GetSeconds(), GetMinutes() or GetHours() to the Date() syntax like this example.
var seconds = new Date().getSeconds();
The above code will return a number between 0 and 59 and store it inside the variable ’seconds’.
Getting the angle
Next we have calculate the angle for each hand. In the case of the seconds and minutes which have 60 increments per rotation we just divide 360 by 60 which gives us 6. This means that for each second or minute we have to rotate the hand by 6 degrees. We’re going to to store this equation inside another variable. For the seconds it will look like this.
var sdegree = seconds * 6;
The hour hand throws up a different scenario. Because there are 12 increments per rotation the angle for each hour is 30 degrees. That’s 360/12=30. Now that would be simple if a clocks hour hand moved in hour increments but it doesn’t. It moves in smaller amounts based on the minute value. Say at 4:30 the hour hand will be half way between 3 and 4. So how do we do this.
Here’s the code.
var hdegree = hours * 30 + (mins / 2);
Basically we’re going to add the current number of minutes divided by two which should give us a number between 0.5 and 29.5 (’rotate’ can handle all floating point numbers) this puts the hand somewhere between any given 30 degree (hour) increment.
Example:
2.40 would be:
2 * 30 = 60 degrees
+ 40 / 2 = 20 degrees
——— — ———-
hdegree = 80 degrees
I did think that the clock might explode when it got past 12 as it would be a number higher then 360 but it worked fine.
So now we’ve figured the math lets inject the new CSS.
Set the style
Here is the CSS3 rotate as if it were in a style sheet.
#sec { -webkit-transform: rotate(45deg); }
Here it is injected by jQuery.
$("#sec").css("-webkit-transform", “rotate(45deg)” );
The problem we have here is getting the variable ’sdegree’ (which holds our angle) into this syntax to replace the (45deg). At first I just tried putting the variable between the brackets but it wouldn’t have it. To make this work we need to build a ’string’ inside another variable called ’srotate’ and completely replace the second argument.
Here’s how we make it.
var srotate = "rotate(" + sdegree + "deg)";
The jQuery will now be written as this.
$("#sec").css("-webkit-transform", srotate );
Putting it all together (in time!)
The whole jQuery code looks like this.
$(document).ready(function() {
setInterval( function() {
var seconds = new Date().getSeconds();
var sdegree = seconds * 6;
var srotate = "rotate(" + sdegree + "deg)";
$("#sec").css("-webkit-transform", srotate );
}, 1000 );
setInterval( function() {
var hours = new Date().getHours();
var mins = new Date().getMinutes();
var hdegree = hours * 30 + (mins / 2);
var hrotate = "rotate(" + hdegree + "deg)";
$("#hour").css("-webkit-transform", hrotate );
}, 1000 );
setInterval( function() {
var mins = new Date().getMinutes();
var mdegree = mins * 6;
var mrotate = "rotate(" + mdegree + "deg)";
$("#min").css("-webkit-transform", mrotate );
}, 1000 );
});
Notice how we’ve used a JavaScript setInterval so the function is run every second. The variables that get the time data have to be inside the function so they update too. If not they would only gather that data on page load once, making a pretty rubbish clock.
Our clock should now work (in Safari).
Alternatives
Flash is the one that comes to mind, although unless you have Actionscript fingers id give it a seat at the back.
In the end
So there it is people, probably the only practical use for the new CSS3 property transform:rotate.
What are you waiting for ! give some of the new CSS3 features a try!
Posted on October 29, 2008 - by admin
The Best sIFR Alternative - Typeface
sIFR has been great… Say good bye to it thou, because there is a new alternative in town! Typeface does everything sIFR does but better. I have been fooling around with it and now its your turn to use this superior JavaScript over text repalcement.
How to use it
1. Download it
Download it from here and include it on your page. Include it after any external stylesheets.
2. Find a font you want to use
David offers three you can download and use. Otherwise, go out and find a TrueType font that you like (that you can use without breaking any copyright laws!). For my example, I snagged a free on off DaFont: Qlassik. (* problematic, see above)
3. Include it on your page
Then run it through the convertor (at the bottom of the page). This will result in a new js file, include that on your page after the typeface.js file. Remember again these should come after your stylesheets
<script type="text/javascript" src="js/typeface-0.10.js"></script>
<script type="text/javascript" src="js/qlassik_medium_regular.typeface.js"></script>
4. Starting using it in the markup
Now you are ready to start using it! Any text you want to use the new font, you’ll need to give a class name of “typeface-js” and then an inline styling statement referencing the new font name.
<h1 class="typeface-js" style="font-family: 'Qlassik Medium'">
Testing a Headline
</h1>
You’ll need to reference the font by its proper name. I find the easiest way to find out its proper name is to install it and then find it in the font menu of any open application.
Thoughts
I’ve been playing with this for maybe one hour, so I’d not going to make any snap judgements or recommendations, but it seems pretty cool so far. Something feels neat about the fact that it’s just JavaScript, not both JavaScript AND Flash like sIFR. or JavaScript AND PHP like FLIR.
I also kind of dig how copy and paste still works on browsers that support <canvas>.
It is also pretty easy to get started! Let me know what you all think.


