Wednesday, 30 November 2011

Hello World JBox2D with JavaFX 2.0

<<JBox2D Tutorial

This is a simple application to get your hands wet with JBox2D and JavaFX 2. I have chosen JavaFX 2.0 for GUI due to its power and simplicity. In this application user can draw different shapes, these shapes works as a hurdles. When user clicks on the  “Start” button, balls starts falling, bouncing and reacting to the hurdles in a very natural way.

You can click here to launch this applications! If JavaFX 2 runtime is not installed on your  PC then it will prompt you for installation. Launch this application and try drawing different hurdles and see how balls reacts to them. You can also click here to download the source code. Please note this is my first program in JBox2D and JavaFX so it might not be following all coding standards. So, your suggestions and feedback will help me to improve on this, so please leave your comments and rating at the end of this post.

If you are not able to launch the application from above link for any reason then this is a sample video of Hello World JBox2D with JavaFX 2.0application.

These are few sample snapshots of Hello World JBox2D with JavaFX 2.0 application.

JBox2D world, Ground, walls and balls are the main component of this application.

JBox2D World is the main component of any JBox2D application. Memory, objects and simulations are managed by the JBox2D World object. Gravity and the doSleep are two parameters of World object. If doSleep is set to true JBox2D world will allow bodies to sleep when they come to rest.

Ground is a bottom most part of application screen. If ground is not created then balls will travel downwards infinitely. Also left and right walls are created so balls will not move out of the viewable screen area. 

These are the code snippets for Hello World JBox2D with JavaFX 2.0.  Please let me know if you have any queries on some part of code. I will be happy to answer.

package jfxwithjbox2d;

import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.paint.LinearGradient;
import javafx.scene.shape.Circle;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;

 * @author dilip
public class Ball{

    //JavaFX UI for ball
    public Node node;
    //X and Y position of the ball in JBox2D world
    private float posX;
    private float posY;
    //Ball radius in pixels
    private int radius;
     * There are three types bodies in JBox2D – Static, Kinematic and dynamic 
     * In this application static bodies (BodyType.STATIC – non movable bodies) 
     * are used for drawing hurdles and dynamic bodies (BodyType.DYNAMIC–movable bodies) 
     * are used for falling balls
    private BodyType bodyType;

    //Gradient effects for balls
    private LinearGradient gradient;
    public Ball(float posX, float posY){
        this(posX, posY, Utils.BALL_SIZE, BodyType.DYNAMIC,Color.RED);
        this.posX = posX;
        this.posY = posY;

    public Ball(float posX, float posY, int radius, BodyType bodyType, Color color){
        this.posX = posX;
        this.posY = posY;
        this.radius = radius;
        this.bodyType = bodyType;
        this.gradient = Utils.getBallGradient(color);
        node = create();
     * This method creates a ball by using Circle object from JavaFX and CircleShape from JBox2D
    private Node create(){
        //Create an UI for ball - JavaFX code
        Circle ball = new Circle();
        ball.setFill(gradient); //set look and feel 
         * Set ball position on JavaFX scene. We need to convert JBox2D coordinates 
         * to JavaFX coordinates which are in pixels.
        ball.setCache(true); //Cache this object for better performance
        //Create an JBox2D body defination for ball.
        BodyDef bd = new BodyDef();
        bd.type = bodyType;
        bd.position.set(posX, posY);
        CircleShape cs = new CircleShape();
        cs.m_radius = radius * 0.1f;  //We need to convert radius to JBox2D equivalent
        // Create a fixture for ball
        FixtureDef fd = new FixtureDef();
        fd.shape = cs;
        fd.density = 0.9f;
        fd.friction = 0.3f;        
        fd.restitution = 0.6f;

        * Virtual invisible JBox2D body of ball. Bodies have velocity and position. 
        * Forces, torques, and impulses can be applied to these bodies.
        Body body =;
        return ball;

package jfxwithjbox2d;

import java.util.Random;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyType;

 * @author dilip
public class JFXwithJBox2d extends Application {

     * @param args the command line arguments
    public static void main(String[] args) {
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello JBox2d World!");
        final Group root = new Group(); //Create a group for holding all objects on the screen
        final Scene scene = new Scene(root, Utils.WIDTH, Utils.HEIGHT,Color.BLACK);
        //Ball array for hold the  balls
        final Ball[] ball = new Ball[Utils.NO_OF_BALLS];
        Random r = new Random(System.currentTimeMillis());
         * Generate balls and position them on random locations.  
         * Random locations between 5 to 95 on x axis and between 100 to 500 on y axis 
        for(int i=0;i<Utils.NO_OF_BALLS;i++) {
            ball[i]=new Ball(r.nextInt(90)+5,r.nextInt(400)+100);
        //Add ground to the application, this is where balls will land
        Utils.addGround(100, 10);
        //Add left and right walls so balls will not move outside the viewing area.
        Utils.addWall(0,100,1,100); //Left wall
        Utils.addWall(99,100,1,100); //Right wall
        final Timeline timeline = new Timeline();

        Duration duration = Duration.seconds(1.0/60.0); // Set duration for frame.
        //Create an ActionEvent, on trigger it executes a world time step and moves the balls to new position 
        EventHandler<ActionEvent> ae = new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {
                        //Create time step. Set Iteration count 8 for velocity and 3 for positions
             , 8, 3); 
                       //Move balls to the new position computed by JBox2D
                       for(int i=0;i<Utils.NO_OF_BALLS;i++) {
                            Body body = (Body)ball[i].node.getUserData();
                            float xpos = Utils.toPixelPosX(body.getPosition().x);
                            float ypos = Utils.toPixelPosY(body.getPosition().y);

         * Set ActionEvent and duration to the KeyFrame. 
         * The ActionEvent is trigged when KeyFrame execution is over. 
        KeyFrame frame = new KeyFrame(duration, ae, null,null);


        //Create button to start simulation.
        final Button btn = new Button();
        btn.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {

        //Add button to the root group

        //Add all balls to the root group
        for(int i=0;i<Utils.NO_OF_BALLS;i++) {
        //Draw hurdles on mouse event.
        EventHandler<MouseEvent> addHurdle = new EventHandler<MouseEvent>(){
            public void handle(MouseEvent me) {
                    //Get mouse's x and y coordinates on the scene
                    float dragX = (float)me.getSceneX();
                    float dragY = (float)me.getSceneY();
                    //Draw ball on this location. Set balls body type to static.
                    Ball hurdle = new Ball(Utils.toPosX(dragX), Utils.toPosY(dragY),2,BodyType.STATIC,Color.BLUE);
                    //Add ball to the root group

import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;

 * @author dilip
public class Utils {
    //Create a JBox2D world. 
    public static final World world = new World(new Vec2(0.0f, -10.0f), true);
    //Screen width and height
    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    //Ball radius in pixel
    public static final int BALL_SIZE = 8;
    //Total number of balls
    public final static int NO_OF_BALLS = 400; 
    //Ball gradient
    private final static LinearGradient BALL_GRADIENT = new LinearGradient(0.0, 0.0, 1.0, 0.0, true, CycleMethod.NO_CYCLE, new Stop[] { new Stop(0, Color.WHITE), new Stop(1, Color.RED)});
    //This method adds a ground to the screen. 
    public static void addGround(float width, float height){
        PolygonShape ps = new PolygonShape();
        FixtureDef fd = new FixtureDef();
        fd.shape = ps;

        BodyDef bd = new BodyDef();
        bd.position= new Vec2(0.0f,-10f);

    //This method creates a walls. 
    public static void addWall(float posX, float posY, float width, float height){
        PolygonShape ps = new PolygonShape();
        FixtureDef fd = new FixtureDef();
        fd.shape = ps;
        fd.density = 1.0f;
        fd.friction = 0.3f;    

        BodyDef bd = new BodyDef();
        bd.position.set(posX, posY);
    //This gives a look and feel to balls
    public static LinearGradient getBallGradient(Color color){
            return BALL_GRADIENT;
            return new LinearGradient(0.0, 0.0, 1.0, 0.0, true, CycleMethod.NO_CYCLE, new Stop[] { new Stop(0, Color.WHITE), new Stop(1, color)});
    //Convert a JBox2D x coordinate to a JavaFX pixel x coordinate
    public static float toPixelPosX(float posX) {
        float x = WIDTH*posX / 100.0f;
        return x;

    //Convert a JavaFX pixel x coordinate to a JBox2D x coordinate
    public static float toPosX(float posX) {
        float x =   (posX*100.0f*1.0f)/WIDTH;
        return x;
    //Convert a JBox2D y coordinate to a JavaFX pixel y coordinate
    public static float toPixelPosY(float posY) {
        float y = HEIGHT - (1.0f*HEIGHT) * posY / 100.0f;
        return y;
    //Convert a JavaFX pixel y coordinate to a JBox2D y coordinate
    public static float toPosY(float posY) {
        float y = 100.0f - ((posY * 100*1.0f) /HEIGHT) ;
        return y;
    //Convert a JBox2D width to pixel width
    public static float toPixelWidth(float width) {
        return WIDTH*width / 100.0f;
    //Convert a JBox2D height to pixel height
    public static float toPixelHeight(float height) {
        return HEIGHT*height/100.0f;

Please try this application and let me know your feedback/queries. Let me know if you find it difficult to build and run this application, I will be happy to help you.

JavaFX 2 books

Tuesday, 22 November 2011

Web Performance With Flash And HTML5

Web Performance With Flash And HTML5

By Kevin Darwin

So, Flash is a vibrant platform that offers a high degree of rich functionality, some of it best-of-breed. Sites and applications developed with Flash are available to virtually every non-mobile Web user, and likely to be available for most mobile users before long, except for those using Apple products.
HTML5 is an exciting, evolving Web coding language with extensive support from all of the Internet's heavy hitters - Google, Apple, Microsoft (albeit slowly), Mozilla, Opera, and yes, even Adobe. It promises to simplify and speed-up both the Web development and Web browsing experience, has native capability to handle multimedia and rich Internet functionality without external plugins, and has ambitions to be the technology that finally bridges all devices, mobile included.
A number of leading Internet voices argue that it's not an either-or scenario. Flash is the best platform for some applications, and HTML5 for others. But how is a developer to decide what the best technology is for the project that's in front of them? Assuming A) that the technology can perform the desired function and B) that the end product is available on user devices, it gets down to a matter of performance.
See HTML5 run

Because it's an open technology (with the possible exception of video), HTML5 promises to lend itself to the robust performance monitoring, measurement, and diagnosis that's been available for other open Web technologies. And it is expected that the advances found in HTML5 will, if used judiciously, be a boon to overall page performance.
Aside from any inherent speed gains, another big advantage of HTML5 vis-�-vis Flash is that, because it is an open technology, real browsers can be deployed in the field to measure and record virtually all of its activity and performance. As has been the case with HTML in all its flavors, and JavaScript, AJAX, etc., performance issues are transparent, and problem sources are more readily visible. There are far fewer black holes that require deep diagnosis.
One of the most anticipated features of HTML5 - and one of the most debated - is the ability to handle audio and video natively in the browser. A few simple lines of code is all it takes to embed A/V files, and, once browsers are updated to handle HTML5, the user would need no special plug-ins to run the files.
As mentioned above, Flash is by far the dominant force in online video. But HTML5 is already making inroads. Vimeo has introduced HTML5 video capability in a new universal player, enabling its videos to be viewed on mobile devices, including those from Apple. And Google has introduced a new, HTML5 mobile version of its site,, which is promoted as delivering better video with a better interface than Apple's own YouTube app.
Keynote Systems - Web performance
mobile website testing, web load testing and measurement of your web sites online performance from inside and outside the firewall all the way to the actual end-user.

Article Source:

Sunday, 20 November 2011

Snapshot: The Wacky History Behind 3D Television Technology

Snapshot: The Wacky History Behind 3D Television Technology

Snapshot: The Wacky History Behind 3D Television Technology

By Justin Hanus

How did our path to 3D TV get started? Was it because of some fluke? Or was this the plan all along?

Below I'll outline the history of 3D TV technology in this article.

Prior to 1900

The road to 3D TV technology all got started way back in 1844 when David Brewster invented the stereoscope, which allowed photographed objects to be seen in 3D.

Fast forward 11 years and the Kinematascope was born in 1855 allowing a camera to capture 3D images in motion.

Right before the turn of the century, renowned British film maker William Friese-Greene took things a step further by securing a patent for the process of 3D movie production. His patent made it possible for a person to see a 3D image from two films positioned perpendicularly to each other.

1900 to 1935

Around 1915, film makers produced the world's first 3D movie, which could be viewed via 3D glasses with two colored lenses.

This in turn became a prelude to Robert Elder and Harry Fairall's mainstream film masterpiece 'The Power of Love', which is known as the first 3D film ever produced.

This was followed by the first color movie utilizing 3D technology in 1935.

1935 to 1960

Due to World War II there wasn't much in terms of the advancement of 3D technology until John Baird showcased the first ever 3D TV to the world in 1958. His research which eventually led to his creation of the 3D TV was heavily influenced by the success of 3D movies (Bwana Devil, House of Wax, and Dial M for Murder) that were released in the early 1950s.

1960 to 1970

With the evolution of 3D technology known as Space Vision, which takes two images and puts them one on top of another on a strip, a single projector could be used instead of two cameras making the production of 3D movies all the easier. As a side note, the first movie created with Space Vision was 'The Bubble' although it was not received well by critics.

1970 to 1990

In 1970, Stereovision was developed by Chris Condon and Allan Silliphant using 35mm film strip to create 3D imagery.

The 1980s saw such titles as Jaws and Friday the 13th part III released as 3D versions.

IMAX was born allowing viewers to watch 3D movies with the absence of eye fatigue.

1990 to 2010

IMAX continued on with its popularity to audiences worldwide by releasing two highly acclaimed movies 'Into the Deep' and 'Wings of Courage'.

Hollywood finally got into the act once 2000 rolled around by releasing Ghosts of the Abyss, Spy Kids 3D: Game Over and The Polar Express.

By 2009, 3D technology finally made it into our homes from the theaters with various broadcasters jumping on the bandwagon.

2010 to???

The sky is the limit as we move forward to a 3D technology experience that will be like none other.

For more relevant information about 3D TVs, click here: 3D TV.

Article Source:

Friday, 18 November 2011

Build Your Own Robots at Home

Build Your Own Robots at Home

Build Your Own Robots at Home

By James Cott

The Time Is Right

The field of hobby robotics is more exciting today than ever before. The day when you will have a humanoid, walking, talking robot in your home that will do your cooking and cleaning looms ever closer. Short of having a real robotic maid or butler, there are many other options that can be built today on just about any budget. If you really want to enjoy a fun, reasonably priced hobby, you should try to build your own robots.

There are many reasons why it makes sense create a robot from scratch rather than buying pre-made ones.


The technology that exists today staggers the mind in not only how advanced it has become, but also in how cheap it is to purchase. There are microcontrollers today that literally replace a room-sized computer of the previous century. The cost for such controllers can be well under $100 for a more-than-capable unit. Some can be purchased as kits to assemble and learn about computer architecture and electronics, others are pre-built units and some even come as single boards that are ready to "plug and play."

Sensors for hobby robots have increased in functionality while they have also reduced in price. It has gotten to the point where advanced sensors like ultrasonic range detectors and infrared distance sensors even come with robotic toys like the Lego Mindstorms kits. The accuracy of these sensors is astonishing and affords the robotic hobbyist with very high-precision instruments capable of providing ample functionality on even an entry-level robot.

To program or Not

It was formerly the case that many of these microcontrollers required a high-level understanding of computers, binary math and assembler language programming to operate. This restricted the field to schooled adults or older children with a great deal of mathematics background.

Today, many of these robotic products come with a computer interface that allows "building block" style components to be visually ordered on-screen in a graphical editor which allows even younger children the ability to understand logic programming and control-flow logic structures in an easy to understand format. These same programs usually also allow code-level programming to be performed as the student gains an understanding of the high-level logic. This allows them to get "closer to the metal" of the processor's native language and architecture while providing skill-building opportunities.

Even more interesting for some, is that many of the common hobby robots have their loyal fan following, usually very technical people, who like to push the limits of the platforms. Often you can find compilers or interpreters written to support programming in other languages. This allows the clever and curious inventors to use their robotic for other purposes while learning ever more technical skills. You can often find more than one website devoted to groups like these.

Attack of the Toys

If you are not as interested in learning programming software, you can also take existing toys and use them as a springboard to more advanced uses. Toys like the Furby of yesteryear gained a following by inspired experimenters who took them apart, rewired them, and put them back together in their own vision, to perform functions not intended by the original manufacturers.

Radio controlled toys are also an excellent springboard for robot development as they take care of a common problem with robots, locomotion. One of the persistent problems creating a robot from scratch is how to propel your robot accurately around the room. Motors require careful selection, knowledge of velocity, gearing and other complex formulas in order to operate accurately. Robots like the iRobot Roomba have solved these problems and thus it makes sense to reuse the work they have done rather than re-inventing the wheel. Pun intended!

Also, battery power can be tricky to learn and many of these platforms take the guesswork out of creating rechargable platforms that won't run out of juice after a five minute stroll around your home.

Reusing these technologies allows the experiment to concentrate on higher-level functions like navigation, vision and other robotic applications that may be more appealing to the robotics enthusiast.


If you have been sitting on the sidelines waiting for the opportunity to dive into hobby robotics; I hope you don't wait any longer, but decide to build your own robot this year. There has never been a better time to get started.

Find more valuable resources, tutorials and information for anyone interested in getting started with the hobby of robotics at James' Blog ( You can learn more about the technologies and even submit your robot for inclusion into our online gallery of robots. Please join us for news, reviews. We try to make learning fun!

Article Source:

Best Selling Robot Kits

Best Selling Robot Kits

By Lance D Jepsen

Robotic toys are a lot of fun and entertainment and they can be fantastic educational toys also. Robotic toys have been developed and refined quite a bit since Leonardo da Vinci's model, and the first robot toy was manufactured in 1939 when Westinghouse created Elektro, a human-like robot, and his robot dog companion Sparky. A smaller version, the Omnibot 2000, was a toy robot developed during the 1980's.
A company called WowWee created the most advanced human-like robotic toy hailed the Robosapien in 2004. Priced at under $99 (US), the first cost-effective, mass-produced humanoid sold four million units and gave life to the consumer robot industry.
The robot market has continued to grow at a very rapid pace. In the present day there is an increasing desire of buying and using robots whether it's a toy for our children, a security system or a lawn mower, adults and kids equally share in using them.
Popular Robotic Toys

The Gaming Roboni-i

Robotic toys are fun to own, but they don't actually boast the same multi player functionality that video games presently have. That might all change with the The Gaming Roboni-i, Earth's first-ever programmable gaming robot.
It's simple to customize and is packed with games; play by yourself or against friends with like robots. You can even create your own games, or download games others have made. To set up a multi player game, the robots must link to each other in a group so that they can identify each other. When this occurs, you're able to intermingle with other The Gaming Roboni-i units and play games with them.


Robosapien is a highly developed mixture of personality with technology. Loaded with attitude and brains, Robosapien is the first robot based on the technology of applied biomorphic robotics. The Robosapien is capable of make out objects and even skin tones and recognize when its owner walks into the room. In addition, Robosapien also has internal incline sensors that can end most functions when he is located in unusual positions, such as lying on its back. The nice thing about this humanoid is the ability for him to stand up in instances where he tips over. Robosapien is a programmable, rapid moving robot. The Robosapien has real multi-speed rapid dynamic running, turning, and walking.
Robosapien has four programming modes: right sensor, left sensor, sonic and master program. The right and left sensors are triggered when sensors on their matching sides are triggered, the sonic sensor is activated when the robot hears a sharp noise (and is in the Listen mode), and the master program is triggered from the remote control.

Lego Mindstorms

Lego Mindstorms allows you to make and program robots that can do just about anything. Lego Mindstorms give you the ability to put together your own robots and program them to carry out all kinds of actions. Version 1.0 RCX bricks feature a power adapter jack that allows nonstop operation rather than the narrow operation time when using batteries. In version 2.0 (as well as later 1.0s included in the RIS 1.5), the power adapter jack was taken off. Version 2.0 of the robotics invention kit includes a programming environment that puts a lot of professional programming products to shame. It is easy to understand why a lot of schools are standardizing on the mindstorms kits to teach classes in the field of robotics.

Wrex the Dog

Wrex the Dog's nose functions like a stop button when he is moving and a random activities selection button when he is not. Wrex the Dog is able to scoot about, play and follow commands and run like a real dog. He can turn his head, twitch his ears, pant and even wag his tail.

The First Robotic Arthropod Known As Roboquad

The First Robotic Arthropod Known As Roboquad is a four-legged, spider-like robot with unparalleled mobility and consciousness. The The First Robotic Arthropod Known As Roboquad is built with advanced sensory awareness, helping it respond immediately to the surrounding environment and follow a moving object in any direction, including forward, backwards, and sideways. The First Robotic Arthropod Known As Roboquad, by WowWee Robotics, claims the honor of being the first true robotic arthropod. It is fundamentally an animated robot that has multi-directional movement capabilities and highly developed sensory perception.
The First Robotic Arthropod Known As Roboquad even has an extended battery life for extended missions. Capable of spotting movement from up to 6 feet away with a IRscanner, he can also hunt for and navigate doorways, and distinguish table edges. When the lights go out, The First Robotic Arthropod Known As Roboquad can continue operating, turning on his head-mounted LEDs which lets it move in the dark. The First Robotic Arthropod Known As Roboquad becomes crabby, happy, attentive, standoffish and jumpy as he walks about on any type of floor. The First Robotic Arthropod Known As Roboquad can even dance.

Tread Based Roborover

Tread Based Roborover appears to be WowWee's 2009 successor to their massively popular Tri-Bot robot which appeared first in 2008. The primary difference is that Tread Based Roborover has treads rather than wheels.
Tread Based Roborover is enabled with object recognition. He has forward and rear sensors that prevent him from bumping in to walls. Tread Based Roborover's tread wheels let it maneuver over objects up to a 15-degree gradient, or about an inch high. Tread Based Roborover is an lively tread based friend with a timid but inquisitive nature, his personality grows and becomes more self-confident as you play with him. He is always eager to be on the move or play games with you. Tread Based Roborover has several distinct modes: explore, lookout, standby and sleep. Explore mode does just what you would expect; Tread Based Roborover navigates around the room autonomously while it avoids running into objects. Sensor-based LED headlights will automatically turn on if it's dark. The Tread Based Roborover features a mixture of vocal content and driving-based games.

The Roving Rovio Security Robot

The Roving Rovio Security Robot, allows you to be in two places at one time! WowWee The Roving Rovio Security Robot includes a WiFi connection which allows you drive it from anywhere in the world given that you have a web capable mobile phone or a PC with internet connection. The Roving Rovio Security Robot's built-in LED headlight will help you steer it even in faintly lit locations, so you will always know what is going on at home or at the office. Its skull-mounted, movable camera and wide range of vision allow you to see and hear precisely what The Roving Rovio Security Robot sees and hears, on your computer screen, anyplace in the world!
No need to be concerned about The Roving Rovio Security Robot running low on power while you're gone - the self-docking feature allows you to send The Roving Rovio Security Robot back to the charging dock to recharge, with the tap of a button in your internet browser. Once it's done charging, The Roving Rovio Security Robot is ready to continue watching your home or office.
Find out more about the fascinating world of robotics as well as popular robots that sell for less than $30 by going to buy robot toy [].

Article Source:

Thursday, 17 November 2011

Getting started with HTML5 – Input Types

I had my first hands on experience with HTML5 and I am quite impressed with it.  HTML5 will definitely change the way we build web sites and the way we access them. Most popular browsers and mobile devices have already started supporting some HTML5 features.

To start with, I will cover few basic but interesting features of HTML5.

Please note, I have used Google Chrome browser to test these features.

HTML5 doctype 

To use HTML5, you need to place <!DOCTYPE html> code snippet on the first line of your HTML file.

For example:

<!DOCTYPE html>
<form  method="get">
     Name : <input type="text"  />

HTML5 Input Types

Many new input types are introduced in HTML5. Some of the most interesting input types are as below.

Number -   The number input types is a field which should contain numeric value.  The number input type supports a following validation attributes.
            min – minimum value allowed
            max – maximum value allowed
            step -  Allowed number series between min and max. it means if min=0, max=10 and step=2 then allowed field values will be 0,2,4,6….10.


Even Numbers: <input type=”number” name=”Even” min=”0” max=”10” step=”2”/>

In above example value less than 0 or greater than 10 or odd values like 3,5,7 are considered as invalid values.

Range – The range input type is very similar to number input type. However, it is displayed as slider bar. The range input type supports a following validation attributes.
            min – minimum value allowed
            max – maximum value allowed
            step -  This defines a jump for slider bar. It means if step=5 then slider slides a 5 points at a time.


Zoom : 0 <input type="range" name="zoom" min="0" max="100" step="5"/> 100

In browser, this is represented as below.

Email – The email input type is a field which should contain email address as value. On form submit, value of email field is automatically validated.


Personal Email: <input type="email" name="personalEmail"/>

<input type="submit"/>

If user enters an incomplete/invalid email address then following warning message is displayed.

URL – The url input type is a field which should contain URL address as a value. On form submit, value of url field is automatically validated.


URL: <input type="url" name="myUrl"/>

<input type="submit"/>

If user enters an incomplete/invalid URL address then following warning message is displayed.

Date – The date input type field should contain date as a value. On form submit this field is validated automatically.


Date: <input type="date" name="date"/>

In browser, this is represented as below.

Month – The month input type filed is used for selecting year and month.  On form submit this field is validated automatically.


Month: <input type="month" name="month"/>

In browser, this is represented as below.

Week – The week input type filed is used for selecting year and week.  On form submit this field is validated automatically.


Week: <input type="week" name="week"/>

In browser, this is represented as below.

Time - The time input type filed is used for selecting hours and minutes.  On form submit this field is validated automatically.


Time: <input type="time" name="time"/>

In browser, this is represented as below.

Datetime - The datetime input type filed is used for selecting year, month, day, hours and minutes (UTC time).  On form submit this field is validated automatically.


Date Time: <input type="datetime" name="d_time"/>

In browser, this is represented as below.

Datetime-local  - The datetime-local input type filed is used for selecting year, month, day, hours and minutes (local time).  On form submit this field is validated automatically.


Date Time Local: <input type="datetime-local" name="d_time_local"/>

In browser, this is represented as below.


So, today I have covered few important HTML5 input types. This is only a tip of iceberg. I will cover few more  HTML5 features in my next post. Meanwhile I would recommend you to read Head First HTML5 Programming: Building Web Apps with JavaScript.

Please feel free to post your queries.
There was an error in this gadget