Hand clock using CSS3. Digital clock on CSS3 and jQuery Script digital clock

We have already discussed the creation of dial clocks with using CSS and JavaScript. In this tutorial we will make the same clock using CSS3 to see how new standard changes the approach to developing various effects. The demo for this tutorial will only work in browsers that support the CSS3 property rotate(the demo DOES NOT WORK in IE6).

CSS3 Transform:rotate

Transform:rotate- a new CSS 3 property that allows you to rotate various elements. Using transformations, you can also change the scale of elements, introduce horizontal and vertical distortions, and move elements around a web page. All of this can be animated using the property transition(With different types transitions and duration).

The same actions for animating page elements can be performed using some JavaScript library (for example, jQuery). Of course, with jQuery you can animate the change much more more CSS properties than using transition. But jQuery is a built-in CSS tool, JavaScript libraries are external tools that may not be available. In any case, CSS3 opens up new promising directions for developer development.

Graphic arts

First we need to do GUI for watches. We will have a base and three arrows. All moving parts are cut in Photoshop to dimensions of 600px height and 30px width, and are positioned vertically, and by default the property rotate rotates the element around the center. You can use the property transform-origin in order to set the center of rotation to a different point.

You can use any image you like for the base of the clock. Moving parts are images PNG format with transparency.

Archived with source code demos included PSD file, which contains all the images.


HTML markup

Clock markings - simple unordered list. Each list element contains a moving part and has a corresponding id:

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 also quite simple. Since the moving parts have the same dimensions and starting points, we can declare them together to avoid repetition. Element ul receives relative positioning, which allows absolute positioning for the arrows located within it.

The CSS3 will be applied using a little jQuery code.

JavaScript
  • Getting the time for the clock
  • Calculate and insert CSS styles(angle of rotation) for each element.
  • We update CSS styles at regular intervals.
  • It should be noted that jQuery works great with the new CSS3 properties. Also, since styles are added dynamically, CSS file passes validation as CSS2.1!

    Getting time

    Time can also be obtained from using PHP code, but it will be server time. And JavaScript returns local time user.

    We will receive information using Date() and set all our variables. We will use accordingly GetSeconds(), GetMinutes() or GetHours() For Date() to set seconds, minutes and hours respectively:

    Var seconds = new Date().getSeconds();

    In the above line, a number from the range from 0 to 59 will be obtained and assigned to a variable seconds.

    Determining the angle

    Then you need to calculate the angle of rotation for each arrow. For the second and minute hands, which have 60 positions on the hour circle, we need to divide 360 ​​degrees by 60, which gives us the number 6. That is, each second or minute corresponds to a rotation of 6 degrees. We will store the result of calculations in another variable. For seconds the code looks like this:

    Var degree = seconds * 6;

    For watches, the calculations will be different. Since we have a dial with 12 positions for the hour hand, each hour corresponds to a rotation angle of 30 degrees (360/12=30). But the hour hand must also be in intermediate states, that is, it must move every minute. That is, at 4:30 the hour hand should be halfway between 3 and 4 o'clock. Here's how we'll do it:

    Var hdegree = hours * 30 + (mins / 2);

    That is, we add to the angle of rotation by the number of hours the value of dividing the number of minutes by 2 (which will give us a value in the range from 0.5 to 29.5). Thus, the hour hand will be “rotated” by an angle from 0 to 30 degrees (hour increment).

    For example:

    2 hours 40 minutes -> 2*30 = 60 degrees and 40/2 = 20 degrees. Total: 80 degrees.

    We can assume that the clock will show who knows what after 12, since the rotation value will be more than 360 degrees. But everything works great.

    Now we are ready to insert CSS rules.

    Setting the style

    This is what a CSS3 rule looks like rotate in the style sheet:

    #sec ( -webkit-transform: rotate(45deg); -moz-transform: rotate(45deg); )

    And this is how the code will be inserted using jQuery:

    $("#sec").css(("-moz-transform" : "rotate(45deg)", "-webkit-transform" : "rotate(45deg)"));

    The only problem is to set the resulting angle value in the "sdegree" variable in the syntax instead of 45 degrees. Need to construct a string in another variable srotate and completely replace the second argument. Like this:

    Var srotate = "rotate(" + sdegree + "deg)";

    And the jQuery code will look like this:

    $("#sec").css(("-moz-transform" : srotate, "-webkit-transform" : srotate));

    Putting it all together

    The jQuery code will look like this:

    $(document).ready(function() ( setInterval(function() ( var seconds = new Date().getSeconds(); var sdegree = seconds * 6; var srotate = "rotate(" + sdegree + "deg)" ; $("#sec").css(("-moz-transform" : srotate, "-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(("-moz-transform" : hrotate, "-webkit-transform" : hrotate)); ), 1000); setInterval(function() ( var mins = new Date().getMinutes(); var mdegree = mins * 6; var mrotate = "rotate(" + mdegree + "deg)"; $("#min").css(("-moz-transform" : mrotate, "-webkit-transform" : mrotate) ); ), 1000); ));

    We use JavaScript function setInterval to update styles every second. Variables that receive time values ​​must be updated in it. Otherwise, the clock will become useless garbage on the page.

    Conclusion

    This lesson demonstrates the practical application of the property rotate not related to design.

    This is a simple script that shows the system time on JavaScript simple text. Hours, minutes and seconds separated by a colon - that's all.

    In order to set your own style for the clock, it is enough to define the style for the block with ID - #time. In CSS you can set your own font for the clock, its color and size. If you need not a simple clock, but a more complex one, then look at Flash clocks for the site. Where does the script get the time data from? The time shown is exactly that set on the device.

    Installation

    Paste the following code where you want to see the clock on your site. On uCoz this could be, for example, “Top” or “Bottom of the site”:

    200?"200px":""+(this.scrollHeight+5)+"px");">
    00:00:00


    setInterval(function () (
    date = new Date(),
    h = date.getHours(),
    m = date.getMinutes(),
    s = date.getSeconds(),
    h = (h< 10) ? "0" + h: h,
    m = (m< 10) ? "0" + m: m,
    s = (s< 10) ? "0" + s: s,
    document.getElementById("time").innerHTML = h + ":" + m + ":" + s;
    }, 1000);

    The script will immediately show a line of text with a clock in the place where you installed it. For example, "00:00:00". Seconds, minutes and hours, by the way, are always two-digit, so changing values ​​occurs smoothly.

    Let's make an electronic clock with date and time using jQuery and CSS3 for a small animation.

    HTML

    The markup is simple and flexible. Create a DIV with a class called clock , a DIV with a class called Date that will display the date, and an unordered list containing the hours, minutes, and seconds.

    CSS

    Design styles with small animation:

    Container (width: 960px; margin: 0 auto; overflow: hidden;) .clock (width:800px; margin:0 auto; padding:30px; border:1px solid #333; color:#fff; ) #Date ( font- family: Arial, Helvetica, sans-serif; font-size:36px; text-align:center; text-shadow:0 0 5px #00c6ff; ) ul ( width:800px; margin:0 auto; padding:0px; list- style:none; text-align:center; ) ul li ( display:inline; font-size:10em; text-align:center; font-family:Arial, Helvetica, sans-serif; text-shadow:0 0 5px # 00c6ff; ) #point ( position:relative; -moz-animation:mymove 1s ease infinite; -webkit-animation:mymove 1s ease infinite; padding-left:10px; padding-right:10px; ) @-webkit-keyframes mymove ( 0% (opacity:1.0; text-shadow:0 0 20px #00c6ff;) 50% (opacity:0; text-shadow:none; ) 100% (opacity:1.0; text-shadow:0 0 20px #00c6ff; ) ) @-moz-keyframes mymove ( 0% (opacity:1.0; text-shadow:0 0 20px #00c6ff;) 50% (opacity:0; text-shadow:none; ) 100% (opacity:1.0; text-shadow :0 0 20px #00c6ff; ) )

    JS

    Connecting the jQuery library

    And then our script $(document).ready(function() ( // Create two variables with the names of months and days of the week in the array var monthNames = [ "January", "February", "March", "April", "May ", "June", "July", "August", "September", "October", "November", "December" ]; var dayNames= ["Sunday", "Monday", "Tuesday", "Wednesday" ,"Thursday","Friday","Saturday"] // Create an object newDate() var newDate = new Date(); // Retrieve the current date from the Date object newDate.setDate(newDate.getDate()); // Output day, date, month and year $("#Date").html(dayNames + " " + newDate.getDate() + " " + monthNames + " " + newDate.getFullYear()); setInterval(function() ( / / Create a newDate() object and retrieve the seconds of the current time var seconds = new Date().getSeconds(); // Add a leading zero to the seconds value $("#sec").html((seconds< 10 ? "0" : "") + seconds); },1000); setInterval(function() { // Создаем объект newDate() и извлекаем минуты текущего времени var minutes = new Date().getMinutes(); // Добавляем начальный ноль к значению минут $("#min").html((minutes < 10 ? "0" : "") + minutes); },1000); setInterval(function() { // Создаем объект newDate() и извлекаем часы из текущего времени var hours = new Date().getHours(); // Добавляем начальный ноль к значению часов $("#hours").html((hours < 10 ? "0" : "") + hours); }, 1000); });

    • new Date() - creates new object Date with value current date and current time in your computer browser.
    • setDate() - method sets the day of the month (from 1 to 31), according to local time
    • getDate() - method returns the day of the month (from 1 to 31) for the specified date according to local time
    • getSeconds(), getMinutes() and getHours() - These methods allow you to retrieve the seconds, minutes and hours of the current time in the browser.
    • (seconds< 10 ? "0" : "") + seconds) - добавляет начальный ноль к значению секунд (минут и часов). Символы ? и : включают тернарный (ternary ) оператор. Это специальный оператор, который возвращает значение перед двоеточием, если условие перед вопросом (? ) верно (true ), или значение после двоеточия , если условие неверно (false ).
    • The setInterval function is a standard JavaScript function, not part of jQuery. Executes the code many times, at regular intervals (milliseconds).
    A simple digital clock that will display the time of your system. Everything here is done in JavaScript, so you can edit them into the design. Installing them is as simple as they themselves; you can put them at the top of the site, where you can mostly see them. The plus is, as was said, you can do them as you need, it all depends on the ID - #time where in the HTML Code Panel it works, but everything is more detailed.

    This is their main script:

    200?"200px":""+(this.scrollHeight+5)+"px");">00:00:00


    setInterval(function () (
    date = new Date(),
    h = date.getHours(),
    m = date.getMinutes(),
    s = date.getSeconds(),
    h = (h< 10) ? "0" + h: h,
    m = (m< 10) ? "0" + m: m,
    s = (s< 10) ? "0" + s: s,
    document.getElementById("time").innerHTML = h + ":" + m + ":" + s;
    }, 1000);

    At the very top we see:

    200?"200px":""+(this.scrollHeight+5)+"px");">00:00:00

    Just add bold text and a yellow tint and arrows.

    200?"200px":""+(this.scrollHeight+5)+"px");">"00:00:00"

    And this is what happened:

    So you can see for yourself how everything has changed, and now you can do everything yourself and beautifully arrange it to suit your styles. That others cannot be done, since Flash is on there, that they are not here.

    Now in addition there is a clock on Flash

    200?"200px":""+(this.scrollHeight+5)+"px");">
    .swf">

    So you can choose which ones you like best and install them, because some can be installed in a block, but you like the first ones better, since they are flexible and customizable, which anyone can do.