Thursday, April 10, 2014

Introduce of TypeScript (Part 2)

Lets continues the topic about TypeScript, I am going to introduce interface, class and module.
Interface
Nothing would change the behavious of JavaScript, but it is good stuff for compiler or IDE to perform type checking. Let's see the example.
interface IVector2D {
    x : number;
    y : number;
}

var a : IVector2D = {x:0, y:0}; // Valid
var b : IVector2D = {x:1, y:1, z:1}; // Valid, fulfill the interface
var c : IVector2D = {x:2}; // Compile error, missing number "y"

var a = { x: 0, y: 0 };
var b = { x: 1, y: 1, z: 1 };
var c = { x: 2 };

With the interface, you are more safe to write some advance function, since compiler or IDE warn you when the type is missmatch. Such as the following example.
function addVector2D (v1 : IVector2D, v2 : IVector2D) : IVector2D {
    return {
        x : v1.x + v2.x,
        y : v1.y + v2.y
    };
}
var d = addVector2D(a, b); // {x:1, y:1}
var e = addVector2D(0, 1); // Compile error

Class
JavaScript is a kind of prototype-based object oriented programing, which is quite different from class-based OOP. Before the next standard of JavaScript (ECMAScript 6) become popular in all browser, TypeScript is the easiest ways to make Class in JavaScript.
class People {
    name : string; // public attribute
    constructor (name : string){ // class constructor
        this.name = name;
    }
    greet () : string { // public method
        return 'Hi, my name is ' + this.name;
    }
}

// Subclass Staff which extends People,
// implements an interface is also possible
class Staff extends People {
    post : string;
    constructor (name : string, post: string){
        super(name); // must call the superclass constructor
        this.post = post;
    }
    greet() : string {
        return super.greet() + ' I am a ' + this.post;
    }
}
var me = new Staff('KiLla', 'Programmer');
console.log(me.greet()); // Hi, my name is KiLla I am a Programmer

Module
For better manage the code, and prevent polluting the globle scrope, module pattern is always recommended for large scale system / library. With TypeScript, you can ECMAScript 6 compliance code very easily.
module mod {
    export var attr : number = 0; // use the "export" keyword, just like nodejs
    export function func() {
    }
}
module mod.submod {
    export class myclass {
    }
}
var a = mod.attr;
var b = mod.func();
var c = new mod.submod.myclass();

Introduce of TypeScript (Part 1)

Previously I just learn something new to me, TypeScript (acutally it first introduced in 2012).
TypeScript is a superset of JavaScript, it preserve all syntax of JavaScript, and with something new (eg. modules, class, interface). By means of compilation, the TypeScript is compiled into JavaScript which is still quite readable.
Actually the Offical Site aready provide very clean introduction and tutorial about the language. So today I would only talk about the typing concept and modules class interface.
As we know JavaScript is weak typing language.

var a = 0;
var b = "0";
var c = false;
a == b && b == c; // true

So TypeScript want to solve this issue by adding strong typing concept to JavaScript

// explicitly tell TypeScript compiler
// what is the type of variable a,b,c
var a : any = false;
var b : number = 0;
var c : string = "0";

// OK code since "a" is in "any" type
a = c;

// Cause compilation error (error TS2011: Cannot convert 'number' to 'string'.),
// but it still preserve in js file because it is valid JavaScript
b = c;

var a = false;
var b = 0;
var c = "0";

a = c;

b = c;

Actually the type is only use for compilation warning, or for IDE to know, it is so clear and beautiful. To be more advance, you can also declare function parameters type and return type.
function func(arg1: string, arg2: string) : Array<string> {
    return [arg1, arg2];
}

function func(arg1, arg2) {
    return [arg1, arg2];
}

Tuesday, October 29, 2013

Several ways for dynamic style modification

In web development, you can have many ways to alter the style of the output in run-time, but they may have speed or manageable difference. Let's try using different ways to modify <td> background color.
The first way you may come out with you mind, maybe is the CSSStyleDeclaration object. Simply using element.style. It is straightforward but difficult to manage.
//pure javascript
var tds = document.getElementsByTagName('td');
for(var i = 0; i < tds.length; i++){
    tds[i].style.backgroundColor = 'grey';
}

//jQuery shorthand
$('td').each(function(i, el){
    el.style.backgroundColor = 'grey';
});

The second method is to play with the inline style attribute. Its very simlar with element.style except the style priority.
//pure javascript
var tds = document.getElementsByTagName('td');
for(var i = 0; i < tds.length; i++){
    tds[i].setAttribute('style', 'background-color:grey');
}

//jQuery shorthand
$('td').css('background-color', 'grey');

The third way I can think of is modifying the className. Actually it is quite hot, because it separate the JS ans CSS, it make the web site more manageable. And Object Oriented CSS is also rely on the className. And its performance is good, for example we don't need to loop through all <td> in our test case, we can directly add it to <table> or <body>.
.greyTD td{ background-color:grey }

//pure javascript
document.body.className += ' greyTD';

//jQuery shorthand
$(document.body).addClass('greyTD');

The final method I'd introduced is CSSStyleSheet, we dynamically create <style> and append it into the <head>. It performance is as good as modify the className, but it is more dynamic because no predefined CSS is needed. However, it is more difficult to manage and debug.
//pure javascript
var style = document.createElement('style');
style.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(style);

var sheet = style.sheet ? style.sheet : style.styleSheet;
var rules = sheet.cssRules ? sheet.cssRules : sheet.rules;
var index = rules.length;
if(sheet.insertRule){ // Standard browser
    sheet.insertRule('td{ background-color:grey }', index);
}else if(sheet.addRule){ // IE8 or below
    sheet.addRule('td', 'background-color:grey', index);
}

Monday, October 7, 2013

Animated Responsive Dropdown Menu

Because the navigation bar of Bootstrap provided didn't have and transition effect, so I customize one. Actually it is nearly rebuild the whole UI widget, except the navbar (I tread it as a container) and collapse feature.
PC view of the menu bar.

Mobile view of the menu bar.

Live Demo Here
(You can drag and resize the width of "result" frame in order to view the different visual effect between mobile view and PC view)
As you know, it is good enough to use CSS to build dropdown menu. To make transition animation during hover, you may use CSS3 transition effect. So what is the tricks to make responsive web design? I is nothing difficult but what you need is @media tag in stylesheet. eg:
/* some style for mobile phone view */
.example {
    /* some styles here */
}
/* Style for screen width > 768px,
   Bootstrap tread it as taplet or PC */
@media (min-width: 768px) {
    .example {
        /* some styles here */
    }
}

It is also called mobile first responsive web design, because you may find that the default style is for mobile phone, and the PC style will overwrite it when the screen is wide enough. With this trick, I make two view of the same HTML content, one is the horizontal menu bar, one is the vertical expendable list.
Since in CSS you can only trace the hover event, which is used to show sub-menu in PC view, but in mobile view, we should click on a item and then expend its sub-menu, so what I do next is to add different event handling in different view. Actually it is the main usage of my javascript file, also I extend $.fn to make them controlable by javascript through:
$('.anav-sub').asubnav('toggle');
$('.anav-sub').asubnav('open');
$('.anav-sub').asubnav('close');

Actually it is not very difficult to make such a responsive UI widget, but you may need to spend some times to play with the CSS, the javascript part is relatively simpler. Below is the whole source code of the example:
<!DOCTYPE html>
<html>
<head>
 <title>Animated Responsive Dropdown Menu</title>
 <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
 <link href="anavbar.css" rel="stylesheet">
 <style type="text/css">
  body {
      margin: 10px;
  }
  @media (min-width: 768px) {
   .navbar-ex2-collapse { float: left; }
  }
 </style>
</head>
<body>
 <!-- Bootstrap Menu Bar -->
 <nav class="navbar navbar-default" role="navigation">
   <div class="navbar-header">
     <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
       <span class="icon-bar"></span>
       <span class="icon-bar"></span>
       <span class="icon-bar"></span>
     </button>
     <a class="navbar-brand" href="#">Bootstrap Menu Bar</a>
   </div>
   <div class="collapse navbar-collapse navbar-ex1-collapse">
     <ul class="nav navbar-nav">
       <li><a href="#">Item 1</a></li>
       <li><a href="#">Item 2</a></li>
       <li class="dropdown">
         <a href="#" class="dropdown-toggle" data-toggle="dropdown">Item 3<b class="caret"></b></a>
         <ul class="dropdown-menu">
           <li><a href="#">Item3.1</a></li>
           <li><a href="#">Item3.2</a></li>
           <li><a href="#">Item3.3</a></li>
         </ul>
       </li>
     </ul>
   </div>
 </nav>

 <div class="spacer" style="height:150px;"></div>

 <!-- My animated responsive navigation bar -->
 <nav id="main_navbar" class="navbar navbar-default anavbar" role="navigation">
  <!-- Navbar header for mobile view -->
  <div class="navbar-header">
   <div class="navbar-brand">
    My Menu Bar
   </div>
   <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex2-collapse">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
   </button>
  </div>
     
  <!-- Navbar menu -->
  <div class="collapse navbar-collapse navbar-ex2-collapse">
   <ul id="main_nav" class="anav">
    <li><a href="#">Item 1</a></li>
    <li><a href="#">Item 2</a></li>
    <li>
     <a href="#">Item 3<div class="arrow">+</div></a>
     <ul class="anav-sub">
      <li><a href="#">Item 3.1</a></li>
      <li><a href="#">Item 3.2</a></li>
      <li><a href="#">Item 3.3</a></li>
     </ul>
    </li>
   </ul>
  </div>
 </nav>

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
 <script src="anavbar.js"></script>
</body>
</html>

$(function(){
 var ANAV_CLASS = ".anav",
  ASUBNAV_CLASS = ".anav-sub";
 function getParent(el){
  return $(el).filter(ASUBNAV_CLASS).parent();
 }
 function toggleHandler(event){
  var $this = $(this),
   $subNavbar = $this.children(ASUBNAV_CLASS),
   isVertical = $this.css('float') == 'none' ? true : false;

  if(isVertical && event && event.type == 'click'){
   toggle.call($subNavbar);
   event.preventDefault();
   event.stopPropagation();
  }
  else if(!isVertical && event && event.type == 'mouseenter'){
   toggle.call($subNavbar, true);
  }
  else if(!isVertical && event && event.type == 'mouseleave'){
   toggle.call($subNavbar, false);
  }
 }
 function ASubNav(el){
  this.element = el;
  getParent(el)
   .on('click mouseenter mouseleave', toggleHandler);
 }
 var toggle = ASubNav.prototype.toggle = function(_isOpen){
  var $this = $(this),
   $parent = getParent(this);
   isOpen = typeof _isOpen == 'boolean' ? _isOpen : !$parent.hasClass('open');
  if(isOpen){
   $parent.addClass('open');
   $this.clearQueue().finish().slideDown();
  }else{
   $parent.removeClass('open');
   $this.clearQueue().finish().slideUp();
  }
 };
 ASubNav.prototype.open = function(){
  toggle.call(this, true);
 };
 ASubNav.prototype.close = function(){
  toggle.call(this, false);
 };

 $.fn.asubnav = function(option){
  return this.each(function(){
   var $this = $(this),
    data = $this.data('anav-sub');

   !data && $this.data('anav-sub', (data = new ASubNav(this)));
   if(typeof option == 'string'){
    data[option].call($this);
   }
  });
 }
 $.fn.asubnav.Constructor = ASubNav;

 $(ANAV_CLASS + " " + ASUBNAV_CLASS).asubnav();
});

.anav, .anav-sub {
 position: relative;
 list-style: none;
 margin: 0;
 padding: 0;
}
.anav > li > a,
.anav-sub > li > a {
 text-decoration: none;
 display: block;
}

/* nav collapse button */
.anavbar .navbar-toggle {
 border-color: #ddd;
}
.anavbar .navbar-toggle:hover {
 background: #ddd;
}
.anavbar .navbar-toggle .icon-bar{
 background: #ccc;
}

/* navbar div */
.anavbar {
 min-height: 40px;
 background: background-color: #f8f8f8;
    border: 1px solid #e7e7e7;
}

/* 1st layer ul */
.anav {
 float: left;
 display: block;
 width: 100%;
}
.anav > li {
 position: relative;
}
.anav > li > a {
 padding: 10px 5px;
 color: #777;
}
.anav > li:hover > a {
 color: #333;
}

/* 2nd layer ul */
.anav .anav-sub {
 overflow: hidden;
 display: none;
 white-space: nowrap;
}
.anav .arrow{
 display: inline-block;
    height: 0;
    width: 0;
    overflow: hidden;
    vertical-align: middle;
    margin-left: 4px;
    background: transparent;
    border-top: 4px solid #777;
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;
    border-bottom: 0 solid transparent;
}
.anav > li:hover .arrow {
    border-top-color: #333;
}
.anav .anav-sub > li > a {
 padding: 5px 15px;
 color: #777;
}
.anav .anav-sub > li:hover > a {
 color: #333;
}

/* Responsive */
@media (min-width: 768px) {
 .anav > li { float: left; width: auto; }
 .anav > li > a { padding: 15px; min-width: 85px; text-align: center; }
 .anav .anav-sub {
  position: absolute;
  -webkit-border-radius: 0 0 4px 4px;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 6px 12px rgba(0,0,0,0.175);
  min-width: 160px;
 }
 .open > .anav-sub { padding-bottom: 4px; border: 1px solid #ccc; }
 .anav .anav-sub > li > a { padding: 5px 20px; min-width: 85px; color: #333; }
 .anav .anav-sub > li:hover > a { background: #428bca; color: #fff; }
}

Friday, September 27, 2013

Twitter Bootstrap - Super fast development for responsive website

In this week, what makes me so exciting is not D3 again, although I still have some skills about D3 which I would like to share, I'll talk about another front-end UI framework in this post, the Twitter Bootstrap. According to the official slogan, Bootstrap is a sleek, intuitive, and powerful mobile first front-end framework for faster and easier web development. Actually, Bootstrap is base on jQuery, and is not something new. But when I accidentally had a chance to study it, I really feel exciting.
The first selling point of Bootstrap is rapid development. It can really boost up the development of front-end design, it remedies the weakness of layout design in jQuery. Just with some well formatted HTML (no javascript), you can get a good looking and interactive web page, with navigation bar and slideshow banner or other basic website element.
The second selling point of Bootstrap is responsive web design, actually is its greatest selling point. It makes you web page fit to all kind of devices. It automatically change the look and view according to you devices's resolution, so you would get well-fit outlook adaptive to you mobile phone, tablet or PC, but would not affect you functionality.
Actually, although Bootstrap is good, it can't satisfy my desire. Because I want a responsive animated navigation bar, so I try to customize one. Through studying how Bootstrap is implemented, I learnt a lot about how to build you own jQuery widget, how to write response web design and also some tricks to play with CSS. Since it isn't quite related to Bootstrap, and I need times to simplify my code I'll do it in the next blog post.

Sunday, September 22, 2013

D3 - My first bar chart

In this post, I'll use a simple bar chart to briefly introduce how to use D3, and the concept of the 3 states in data life cycle, enter, update and exit. Some helper function me may touch here, such as select, scale, axis and on, but the I'll not explain them in details.

Live Demo Here
var myData = [], // Bar chart's data source
    max = 10, // Y-axis maximum value
    margin = {top: 20, right: 20, bottom: 40, left: 40},
    width = 400, height = 300;

function randData(){ // Add random number to myData
    myData.push(Math.ceil(Math.random() * max));
}
function resetData(){ // Reset myData
    myData = [];
}

In the very beginning, I declare an array myData, which represents the data in the bar chart. Also there are some setting like, maximum value, margin of the chart, the dimension of the bar chart and 2 function to manipulate the data.
var y = d3.scale.linear() // Scale of y coordinate
    .domain([0, max])
    .range([height-margin.bottom, margin.top]);
var h = d3.scale.linear() // Scale of height
    .domain([0, max])
    .range([0, height-margin.top-margin.bottom]);

Then I define 2 scale object. Actually it is just a function to map a input domain data, into output range data. It is useful when you need to know a bar should locate to which x,y coordinate in the <svg> element, and how many pixel should be the high of the bar.
var svg = d3.select('#result').append('svg') // Create <svg> HTML Element
    .attr('width', width)
    .attr('height', height);
var xAxisLine = svg.append('g') // Create X-axis line
    .attr('class', 'axis')
        .append('line')
            .attr('x1', margin.left)
            .attr('y1', height - margin.bottom)
            .attr('x2', width - margin.right)
            .attr('y2', height - margin.bottom);
The above code show how I append <svg> and <line> element, then change their attributes. Actually the syntax is very similar to jQuery, I guess there is no difficulty for you to follow.
var yAxis = d3.svg.axis() // D3 axis object
    .scale(y)
    .orient("left");
var yAxisLine = svg.append("g") // Create Y-axis line
    .attr('class', 'axis')
    .attr("transform", "translate("+margin.left+",0)")
    .call(yAxis);
In previous code, you may found that I need 7 lines of code to create a single <line> element in order to represent the X-axis. So would it be very trouble to draw a axis with ticks and value labels? No, D3 provide a axis object to auto generate a axis.
function render(){
    var x = d3.scale.ordinal() // Create scale of X-axis
        .domain(myData.map(function(d, i){ return i; }))
        .rangeRoundBands([margin.left, width-margin.right], 0.1);
    var bar = svg.selectAll('.data') // Bind data
        .data(myData);
    bar.enter().append('rect') // Data enter
        .attr('class', 'data')
        .attr("width", x.rangeBand())
        .attr("height", h(0))
        .attr('x', function(d, i){ return x(i); })
        .attr('y', y(0));
    bar.transition() // Data update
        .duration(1000)
        .attr("height", h)
        .attr("width", x.rangeBand())
        .attr('x', function(d, i){ return x(i); })
        .attr('y', y);
    bar.exit().transition() // Data exit
        .duration(500)
        .attr("height", h(0))
        .attr('y', y(0))
        .remove();
}

Finally, we come to the main course of this post, use data-driven methodology to draw the bars. At the beginning of this function, I define a X-axis scale base on the number of data.
Then it comes to the data binding, in D3 each data element would bind to a DOM element. After data binding, we can define the actions when data enter, update and exit.
Data Binding (line 43,44) - so you can find I use function data for the selection result. This function allow 2 arguments, the first is an array of data, the second is optional, a function for identify the data element, default is a function return the array index of a data element.
Data Enter (line 45) - in D3 we always bind data to DOM element, and D3 would know which data is new / insert to the dataset. So we call enter to tell D3 we need to do action for those new data, and immediate call append to create a container for the data.
Data update (line 51) - since dataset may change time to time, so base on the dataset, the DOM element may need to update. Update would include both new data and existing data, so you can see I directly change attributes on the DOM element. The transition and duration call is mainly related to the animation for the bar shift when there is new entry data.
Data Exit (line 57) - it describes the data which is removed compare to the previous dataset. So what I need to do is just tell D3 to hide the bar for exiting data, and then remove them from DOM tree.
d3.select('input[type=button]').on('click', function(){
    randData();
    render();
});
d3.select('input[type=reset]').on('click', function(){
    resetData();
    render();
});

Lastly, I bind 2 onclick function for the button, so we can add and reset the data, all the stuff is just the same as jQuery.
To conclude, make use of the data binding, enter, update and exit allow us to render the data representation as batch. Actually, if you need to build a customize axis, you can also trend the ticks' values as data of the axis, and render it through its own life cycle.
The whole source code is as below:
<!DOCTYPE html>
<html>
<head>
    <style>
    svg {
        border: 1px solid black;
    }
    .axis line, .axis path{
        fill: none;
        stroke: black;
        shape-rendering: crispEdges;
    }

    rect.data {
        fill: steelblue;
    }
    </style>
</head>
<body>
    <div id="result"></div>
    <input type="button" value="Add Data" />
    <input type="reset" value="Reset" />
    
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="main.js"></script>
</body>
</html>

var myData = [], // Bar chart's data source
    max = 10, // Y-axis maximum value
    margin = {top: 20, right: 20, bottom: 40, left: 40},
    width = 400, height = 300;

function randData(){ // Add random number to myData
    myData.push(Math.ceil(Math.random() * max));
}
function resetData(){ // Reset myData
    myData = [];
}

// Tha setting of the bar chart
var y = d3.scale.linear() // Scale of y coordinate
    .domain([0, max])
    .range([height-margin.bottom, margin.top]);
var h = d3.scale.linear() // Scale of height
    .domain([0, max])
    .range([0, height-margin.top-margin.bottom]);
var svg = d3.select('#result').append('svg') // Create <svg> HTML Element
    .attr('width', width)
    .attr('height', height);
var xAxisLine = svg.append('g') // Create X-axis line
    .attr('class', 'axis')
        .append('line')
            .attr('x1', margin.left)
            .attr('y1', height - margin.bottom)
            .attr('x2', width - margin.right)
            .attr('y2', height - margin.bottom);
var yAxis = d3.svg.axis() // D3 axis object
    .scale(y)
    .orient("left");
var yAxisLine = svg.append("g") // Create Y-axis line
    .attr('class', 'axis')
    .attr("transform", "translate("+margin.left+",0)")
    .call(yAxis);

// Main function to draw the bar chart's "bars"
function render(){
    var x = d3.scale.ordinal() // Create scale of X-axis
        .domain(myData.map(function(d, i){ return i; }))
        .rangeRoundBands([margin.left, width-margin.right], 0.1);
    var bar = svg.selectAll('.data') // Bind data
        .data(myData);
    bar.enter().append('rect') // Data enter
        .attr('class', 'data')
        .attr("width", x.rangeBand())
        .attr("height", h(0))
        .attr('x', function(d, i){ return x(i); })
        .attr('y', y(0));
    bar.transition() // Data update
        .duration(1000)
        .attr("height", h)
        .attr("width", x.rangeBand())
        .attr('x', function(d, i){ return x(i); })
        .attr('y', y);
    bar.exit().transition() // Data exit
        .duration(500)
        .attr("height", h(0))
        .attr('y', y(0))
        .remove();
}

// Event handler of buttons
d3.select('input[type=button]').on('click', function(){
    randData();
    render();
});
d3.select('input[type=reset]').on('click', function(){
    resetData();
    render();
});

Thursday, September 19, 2013

D3 - Build chart so easy

Today I would like to introduce an interesting library, D3. D3 means "Data Driven Document", which is a javascript data visualization library. With this library, you can very easy to repersent data in a more fancy way. Here are some offical examples.
D3 strong at make use of HTML5 inline SVG to render graphic, so it is not compatible with IE8. Eventhough there is such a limitation, I found that D3 is so easy to use, with great support for animation and interaction, and its key concept of data driven is really good at ploting graph.
The following is an example of a very simple bar chart. Note that since D3 is not a plugin but it is a library, I think use 40 lines code to build a bar chart is pretty good.

var myData = [{name:"A",value:3},
              {name:"B",value:5},
              {name:"C",value:2}];
var margin = {top: 20, right: 20, bottom: 40, left: 40};
var width = 400;
var height = 300;
var x = d3.scale.ordinal()
    .domain(myData.map(function(d){ return d.name; }))
    .rangeRoundBands([margin.left, width-margin.right], 0.1);
var y = d3.scale.linear()
    .domain([0, d3.max(myData, function(d){ return d.value; })])
    .range([height-margin.bottom, margin.top]);
var h = d3.scale.linear()
    .domain([0, d3.max(myData, function(d){ return d.value; })])
    .range([0, height-margin.top-margin.bottom]);
var xAxis = d3.svg.axis()
    .scale(x);
var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(5);
var svg = d3.select('body').append('svg')
    .attr('width', width)
    .attr('height', height);
svg.append("g")
    .attr('class', 'axis')
    .attr("transform", "translate(0,"+(height-margin.bottom)+")")
    .call(xAxis);
svg.append("g")
    .attr('class', 'axis')
    .attr("transform", "translate("+margin.left+",0)")
    .call(yAxis);
var bar = svg.selectAll('.data').append('rect')
    .data(myData);
bar.enter().append('rect')
    .attr('class', 'data')
    .attr("width", x.rangeBand())
    .attr("height", function(d){ return h(d.value); })
    .attr('x', function(d){ return x(d.value); })
    .attr('y', function(d){ return y(d.value); });

Live Demo Here
In the next blog post, I'll dig in to the D3 and explian how to use.