Wednesday, August 2, 2017

How to create horizontal bar chart using d3js JavaScript charting library

I received lot of requests by many d3js beginners about "how to create a horizontal bar chart using d3js" along with sample code. I think I have not posted anything related to d3js after my last article. So almost after 2 months, I am writing this post on d3js. I have prepared a sample code to show the distance in meters covered by every participant in a running race. It's very simple example with distance in meters is on X-axis and participant's names are on Y-axis. Just for the change, I have moved my X-Axis to the top.

Sample code for creating horizontal bar chart in d3js

Step 1 - Append an empty DIV to body with id as "chart"
<!-- horizontal bar chart -->
<div id="chart">  </div>
Step 2 - Prepare JSON data
var data = [{
   "name": "Rohit",
   "value": 120
  }, {
   "name": "Sanket",
   "value": 116
  }, {
   "name": "Vivek",
   "value": 109
  }, {
   "name": "Richa",
   "value": 94
  }, {
   "name": "Ricky",
   "value": 90
  }, {
   "name": "soniya",
   "value": 84
  }, {
   "name": "Nilesh",
   "value": 107
  }, {
   "name": "Sweety",
   "value": 66
Note : This is the data which will be displayed in the chart, your values may change and you can update this JSON as per requirements.

Step 3 - Create self injecting method with two parameters to it - holder & data
You can also give some name to the method and pass the parameters. I am giving the explanation of the steps which I have used in my example so can do the changes in your code if you are comfortable. This method takes care of creating the x and y axis and drawing the rectangle etc.
// code to generate chart goes here.
})("#chart", data);

If you are completely new to d3js and don't know about how to draw x and y axis using SVG then please refer to my first post. In this post, I am explaining the changes required for only the horizontal bar chart.

Step 4 - Once X and Y axis are ready, use below script to generate horizontal rectangles.
So once your axis is ready then you can add following code in order to generate bars on the chart. Basically, you will be generating rectangle elements using d3js methods. In this, we have to specify x-y coordinates, width, and height of each rectangle. Have a look at the below code and you will understand what is happening.
 .attr('class', 'bar barColor')
 .attr('x', function(d) { return x(d3.min(data, function(d) {return +d.value;})); })
 .attr('y', function(d) { return y(; })
 .attr('width', function(d) { return x(d.value); })
 .attr('height', y.rangeBand());
You can check last 4 lines of above code, I am starting the rectangle from the starting point of the x axis which is nothing but the minimum of the d.value from data object. Similarly I am setting the height and width of the rectangle.

I hope this example code will help beginners to understand how svg bar element can be used to generate horizontal bar charts using d3.js. Best of luck.

Friday, February 24, 2017

Dynamically add/remove table rows using jquery

While developing complex DOM structures, many time we come across the designs where we may need to control the height of the HTML table dynamically. In many situations, the requirement is to let users manage the number of table rows. This is really a simple code and can be easily written using JavaScript and jQuery.

Before we move and check the code I want to highlight that one must know the use of jQuery methods such as "append()", "close()" & "remove()". If you know the purpose and working of these methods then this job will be a piece of cake for you.

Click to view Demo

Step 1. Copy below HTML markup for table
<table id="table">
    <tr valign="top" >
      <th scope="row"><label>Label</label></th>
        <input type="text" id="field1" />  
        <input type="text" id="field2" />  
        <a href="javascript:void(0);" class="add">Add</a>    <a href="javascript:void(0);" class="remove">Remove</a>
Note that you will have to keep one row in this table which needs to be cloned dynamically. We can also keep empty table but in that case, we will need to create a DOM object using jQuery. Let's first understand the logic of dynamically adding the rows and later on you can remove first row as well.

Step 2. jQuery code to dynamically add/remove rows of the table
    rowObj = $("#table tr:first").clone();
    $( "#table" ).append(rowObj);

I have used CSS selector rule "#table tr:first" to select the first row of the table. I am using .clone() method on that selector to make a copy of it and saved it in rowObj variable. This object is nothing but a DOM element which we can append to any parent. So next job is to just append the cloned DOM element to the table using "append()" method. Similarly I have used remove() method to dynamically remove the table row.
Wednesday, February 22, 2017

Simple MEAN stack application with sample code

From so many years JavaScript has escaped the limelight for the majority and was being seen as just a language to validate forms and show alerts and some other small tasks on the client side. But now JavaScript has become very powerful and it's capable enough to make you a full stack web developer. Yes, if you know JavaScript you can create web server, create beautiful UI to handle user interaction and can also write powerful API to handle all the data sent through web forms and save the data into the database.
Sounds interesting? Go through the complete tutorial to understand how can we implement a complete web application and server using JavaScript and MEAN stack.

What is MEAN stack and why you should learn it?
Let's first understand what is the meaning of this MEAN stack and how this can be useful to complete this tutorial. MEAN stack is the stack of technologies which I am going to use in this tutorial. This little bunch of technologies is well enough for writing a complete web application.

M - MongoDB
E - ExpressJS
A - AngularJS
N - Node JS

It's perfectly all right if you are not aware of any of the above technologies I am going to explain everything in detail and step by step manner. Highlevel overview of this tutorial is as follows.
  • Learn to install nodeJS.
  • How to install dependencies using package.json.
  • Create simple directory structure for our first MEAN application.
  • How to include ExpressJS to your nodejs web server
  • Writing your first web form to get inputs from user.
  • Writing your first API using ExpressJS to handle the form data.
  • Installing mondoDB server to store the data.
  • Changing the first API to not only handle the post data but to save it in database.
  • Writing your second API to fetch the records from database and return them in JSON format.

I have used Ubuntu 15.10 while preparing this tutorial so all the steps mentioned here are for Ubuntu and other linux flavors and not for windows. But the code and the main logic will remain same, only installation steps will change for windows users. Soon I will also try to write the steps for windows users as well. Really sorry for not having it right now.

Get set go,

1. Let's start with learning to install nodeJS.
Let's start by installing nodeJS on your linux machine using package manager. Please refer following commands to install nodeJS.
sudo apt-get update
sudo apt-get install nodejs
Above step will install only nodeJS on your machine but we also need some other nodeJS modules in further steps of this tutorial. So let's also have a look at the installation of Node Package Manager. Simply run following command to install NPM.
sudo apt-get install npm
Cool now we have our nodeJS and NPM ready.

2. Lets learn to install dependencies using package.json
In above step we have installed NPM, which will help us to install multiple dependencies of our application very easily. package.json is the file which have the configurations of all the dependencies of the application. So let's see how can we create this file to define dependencies of our app.

For this simply follow the below steps and learn the standard approach of setting up your node project. Let's start by creating the empty directory, I name my application as "user_info" and thus the directory. This application will accept user information so I named it user_info you can change this name.
mkdir user_info
cd user_info
Now let's create the package.json file to write metadata and module dependency of our application. A standard and efficient way to do so is to use the command "npm init". This utility will help you to create your package.json. So just hit this on your command prompt and answer the questions asked on the prompt to complete this step.
npm init
Below is the screenshot of the process to create the package.json.

I hope the process is simple and you have successfully setup your first nodeJS application with the help of NPM. Now you can browse your package.json file and check its contents. It should look something like below image.

Let's add dependencies to this file now.
Now we will update this package.json file to include our application dependenices and later on we will install all of them in a node way. You need to add one extra key called as "dependencies" as shows in below example.
  "name": "user_info",
  "version": "1.0.0",
  "description": "Simple application to save user information",
  "main": "index.js",
  "scripts": {
    "test": "echo \"my first MEAN stack application\""
  "author": "Dhanesh Mane",
  "license": "ISC",
  "dependencies": {
    "body-parser": "latest",
    "express": "latest",
    "mongodb": "^2.2.22",
    "mongoose": "latest"
In above step we have added 4 new dependencies to our project, now its time to install these dependencies by using below command.
npm install
Above command create new directory called as "node_modules" to save all node dependencies. There must be a new directory "node_modules" inside user_info app. please go back to console and check if all your dependencies are installed inside this directory or not. If you can see some files related to MongoDB and ExpressJS then you have your dependencies ready to use.
Lets verify the installation using following commands.

3. Lets create directory structure & some important files
While setting up your first MEAN stack application we should follow a good directory structure, I dont want to be too complex here as its our first application so I have just tried to keep it simople. Just go thgough following 4 steps and setup your structure.

1. Create directory with name "user_info/config".
2. Create empty file with name "user_info/config/database.js".
3. Create directory with name "user_info/models".
4. Create directory with name "user_info/public".

It should look something like below image.

4. Let's include express to your nodejs project and create a web server
Fun begins, let's start writing some code now. From this step we will be writing our web server and the API as most of the installation is done. So simply create a new file and name it as user_info/server.js. First of all, let's see how to include express in our nodeJS project. If you remember we have already installed express dependency in step 2 so now we just need to give its reference to include it in the project. Copy below lines of code and paste it in server.js
'use strict';
// ----- initialization
var express = require('express');
var app = express();


// ----- Routes
app.get('/',function(req, res){
   res.send('my first node server');

// ----- Server
var server = app.listen(3000, function () {
  var port = server.address().port

  console.log('Example app listening on port 3000! go to http://localhost:%s',  port)
Now it's a time to run your first node server. Open the command prompt, go to user_info directory and hit below command to start the server.
node server.js
Once you run above command you should see a message something like this on your prompt --> "Example app listening on port 3000! go to http://localhost:3000". If you see this then your first node server app is running properly.
Go to "http://localhost:3000" on your browser and check what you see on your browser. It must be something similar to below image.

5. Let's create a simple form to accept user inputs
I don't want to explain this step in detail, but you can simply copy below sample code and paste in new file "public/user_info.html"
<!DOCTYPE html>
<html lang="en">
  <title>User Info</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="">
  <script src=""></script>
  <script src=""></script>

<div class="container">
  <h2>Enter User Information</h2>
  <form action="/save_user" method="post">
    <div class="form-group">
      <label for="email">Email:</label>
      <input name="email" type="text" class="form-control" id="email" placeholder="Enter email">
    <div class="form-group">
      <label for="name">Full Name:</label>
      <input name="name" type="text" class="form-control" id="name" placeholder="Enter full name">
    <div class="form-group">
      <label for="grade">Grade:</label>
      <input name="grade" type="text" class="form-control" id="grade" placeholder="Enter Grade">
    <button type="submit" class="btn btn-default">Submit</button>

Check the form in web browser ("http://localhost:3000/user_info.html"), it will look something like below image.

6. Now Let's write the API to handle the form data
If the simple web form is rendering properly on your web browser you can continue with this step. We have 3 fields in that form including email, name and grade. The form action is set to "save_user", so once the form is submitted it will send the data to save_user API. So in order to handle this form data we will need to add a route in our server.js with the name save_user.

Add following two lines at the end of initialization section of server.js.
var bodyParser = require('body-parser');
var urlencodeParser = bodyParser.urlencoded({ extended:false});
Add following route after our default route in which we have displayed the message "my first node server".'/save_user', urlencodeParser, function(req, res){
   var response = {,,
In above step, we have created new end point with name "save_user" using method. If you check the difference between our first & second route you can see there is a change of the method. In first route we have used app.get and in this route we have used because we are expecting some post data as an input for this API to work. This is really straightforward and simple.

In this API we have created a JavaScript variable "response" and simply creating the object by taking the post data with the help of reference like "". We are able to get the POSt data because of the module included in initialization section "body-parser". We can check this module in details later to more about its functions.

We are using "res.end(JSON.stringify(response));" to generate the response of the API. Now you can run the form "http://localhost:3000/user_info.html" in browser and fill all the data and hit enter. This will hit our save_user API and you can see output something similar to below image.

If you are able to see similar screen then congrats you have successfully implemented first cut of your first web service. Till now we have just taken the POST data and returning it in JSON format but what we actually need is to insert these records in database. Usually, the APIs core responsibility is to insert something into the database and to retrieve the data from database, wrap it with the business logic and return in the form of JSON data. So let's add that functionality to pour API to make it complete. For that we need to have MongoDB server, so let's go to our next step and create a new database.

7. Install MongoDB and create a database
Check if its already installed or not by using following command.
mongod --version
If it's giving you error then go ahead and install it using following commands
sudo apt-get update
sudo apt-get install -y mongodb-org
Once this is done, start the database server by using following command
sudo service mongod start

Now let's go to mongo shell (#mongo) & let's create database & users for your database.
use user_info  #this wil create your database with name user_info

8. Lets connect to database using ExpressJS and save the data.
We have already written the API save_user which is currently just fetching the data from POST. But the save_user API is suppose to do more than this, yes we need to connect to the database and save the information coming from the web form to the database.

1. Open the file "user_info/config/database.js" created in step 3.
This file is nothing but the configuration file for our database. We have to specify the MongoDB connection string in following format.

module.exports = {
    remoteUrl : 'mongodb://admin:admin@localhost:27017/userInfo',
    localUrl: 'mongodb://admin:admin@localhost:27017/userInfo'

2.Load the config file in server.js
The database configuration file created in above step needs to be included in server.js to make use of the connection string. As we have created it as a module we can use require() method to include the database and make it available for ExpressJS. Add following line at the bottom of the initialization section of server.js
var database = require('./config/database');   // load the database config

3.Learn to connect MongoDB using mongoose
We have successfully imported the database module in step above. Now we will see how can we use module "mongoose" to connect to the mondoDB database.
Copy following lines and paste them below the require statement of database. The first line we are including the module mongoose and in second line we are making a connection to the database using localUrl. Notice that we have two different connection strings in database.js one is for local setup and one is for remoteUrl, for now you can also keep only one to complete the tutorial.
var mongoose = require('mongoose'); 

4. Lets create "info" model (you can change this name)
Before we start writing the code to save the form data in to the database we will first need to define the model for the form. So lets quickly create new file "info.js" under "user_info/model" and write below model object in that file. Ths object is self explanatory.
var mongoose = require('mongoose');

module.exports = mongoose.model('Info', {
    name: {
        type: String,
        default: ''
    email: {
        type: String,
        default: ''
    grade: {
        type: String,
        default: ''
Once this is done, we will need to include info model in our server.js file. So copy following command and paste at end of the initialization section.
var Info = require('./models/info');

5. Let's save the data into database by rewriting save_user route
As we have our data model ready we can simply replace the save_user route from server.js with the code below. Before copying the code please notice that I have just added one code block "Info.create()" and the POST data is sent to this method. This code block itself does everything and the form data gets stored in the database. We will write one more API after this to check the inserted records.'/save_user', urlencodeParser, function(req, res){
   var response = {,,

        }, function (err, todo) {
            if (err)


6. Fetch the database from MongoDB using ExpressJS and Node
Once the above step is complete your app to save the database into the database using node and ExpressJS is done, but we will add one more API to check all the data inserted with the help of this API. So let's call it as "all_info" API.
copy the code below and put it at the end of routes section of server.js. This is nothing but a new API "all_info" which makes use of info model and find the method which returns all the records of that model.
app.get('/all_info', urlencodeParser, function(req, res){
   Info.find(function(err, infos){



9. Run and test your first MEAN stack application.
  • Restart your node server. ( you can hit control + C to close current session and then again run "node server.js")
  • Open web browser and hit URL "http://localhost:3000/user_info.html"
  • Enter some data in webform and hit submit.
  • This step will save form data in database.
  • Open web browser and hit URL "http://localhost:3000/all_info"
  • This will show you all the data from database, your screen will look something like below screenshot.

Remember above are just APIs, who's job is to return JSON data. You can later on create views and call these API. I will try to cover the view integration in my next post.
Monday, January 30, 2017

Basic SEO checklist before launching your new website

Take a pause. Is your website ready? ask yourself again. Technically it might be, but are you really sure that it's optimized and ready with SEO as well? OK, so now if you are not sure then this article is very important for you and your business. I have worked on more than 15 different business models and optimized 100 plus websites to improve their search engine listings. While working on such a huge number of projects, I realized that there are some very very common things which we need to do irrespective of their business model or type of website. So this is the list of very basic and important things which we should integrate before launching your new business website.

When it comes to SEO, the first thing to learn is, don't be impatient, good things take time. . It's very very difficult to recover from SEO penalty. If search engine ranks your website lower, then bringing it up is a challenge. So while launching your new website it's always better and safest way to check it for common things first and not to rush to make it live. So let's go over the pre-launch SEO checklist & make your website ready for launch.

1. Make sure you have prepared a perfect robots.txt

What is robots.txt? - Many time there are few pages/directories which we don't want any search engine to crawl/index. e.g. some backup files, control panel directories, basically anything which you don't want to appear in search engine result pages.
Why we should do this? - Let search engines have only the good and optimised pages of your website to decide it's ranking. If there are such unnecessary and more number of pages then overall website rankings will be calculated from all these pages, so let only few & important pages be indexed. We also have to control the traffic of search engine crawlers to our website because we don't want our web server to keep serving to web crawlers mainly for the pages which are not important.

How to allow full access in robots.txt file
Following block will allow all crawlers(User-agent: *) to access all files and folders from your web server.
User-agent: *
How to block full website in robots.txt file
Following lines will block all crawlers to access your web site, so nothing will appear in search engine result pages.
User-agent: *
Disallow: /
How to block a multiple folders in robots.txt file
User-agent: *
Disallow: /folder_name1/
Disallow: /folder_name2/
How to block a pages in robots.txt file
User-agent: *
Disallow: /filename.php
How to block all bots except google, Yahoo and Bing
User-agent: *
Disallow: /

User-agent: Googlebot
Allow: /

User-agent: Yahoo-slurp

User-agent: Msnbot
How to add sitemap.xml in robots.txt file
Its always a better practice to have a xml sitemap for your website. Its not mandatory but its good practice. Check the below code to add the sitemap to robots.txt.
Following is the URL of my robots.txt, you can have a look at it while making one for your domain.
You should always test your robots.txt file with the tester provided by Google.
Click here to test your robots.txt file.

2. Non www to www redirect in .htaccess

If you are having 2 different URLs on your website with absolutely same contents then search engines consider it as duplicate content issue. As a best SEO practice, we should always avoid such issues.
Your website's home page can be open with 2 URLs, and Both of these URLs point to the home page of the website so it will be considered as the duplicate content issue. I usually keep 301 permanent redirect from non-www to www using .htaccess file in apache web server. You can copy following code in your .htaccess file.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^ [NC]
RewriteRule ^(.*)$$1 [L,R=301,NC]

3. Redirect index.php to root in htaccess

This is one more URL which can create the duplicate content issue with domain root. Your domain root ( is always pointing to index pages like index.php or index.html so this is another instance where we can have the duplicate content issue. In this case, we do a 301 permanent redirect of index.php to website root. Just copy the lines in below box and paste in your htaccess file.
RewriteRule ^(.*)index\.(php|html?)$ /$1 [R=301,NC,L]
Above rewrite rule will redirect index.html / php to it's root with server response code as 301. the NC flag at the end will make it case case-insensitive, so this is the safest way to achieve this.

4.Content is god - 300 plus words per page is very important

SEO is much difficult these days as most of the old SEO strategies began to fail. Google and other search engines updating their algorithm very frequently and scrapping all old techniques to promote your website.

In order to make a successful website, you have to have a very powerful content writer. Make sure each page is having more than 300 words. Make sure all pages have their unique identity & did not conflict with any other page. Try to generate original contents and do not copy from any other website, if you think this process will take time then don't worry. It's always better to make a perfect website and then launch it rather than launching and later thinking about optimizing.

5. Optimized & unique meta data for every page

I am sure everyone know what a meta data is and how important it is for the website. One important thing to remember while preparing the meta data for your website is, every page must have unique set of keywords and description.
  • Make sure you have proper contents for each keyword you are planning to use in meta keyword.
  • While choosing keywords don't forget long tail keywords
  • Link keywords in contents to respective website page if available.

Tuesday, January 17, 2017

Scale the circle radius in d3js chart on mouseover

D3.js is really an amazing charting library and I think I can't stop writing about it's features and sample codes. D3.js is something like, no limitations on what you can do with charts. You think about it and it's possible with this library. Today while working on one example, I came across a situation where most of the chart area was covered with points and paths because of huge data points. In this case, we can add small animation to the path points. In this type of animation if user mouseover on some data point, then we increase the radius of the circle with transition effect and on mouse out we bring it back to the original radius. So let's learn something about circle animation in this post.

I have tried to explain the code in pictorial way in below image, please check it and first and try to understand the logic.

Check line number 229 in my example to understand how to place the below code block. You will first have to select the circle and then configure its mouseover event as described below.

.on("mouseover", function(d) {  
    .attr("r", 6);


Once this is done, you have to configure the mouse out event to bring circle back to its original size.
Monday, January 16, 2017

Best syntax highlighter for blogs and websites

Few months back I started sharing my codes and programming experience on my blog. I was looking for simple and best solution to highlight the code samples on my blog. There are many online tools which helps you to generate the HTML code which can be directly used on your website with highlighted styles. These online tools works fine, but it generates a lot of HTML and CSS. So I found it's alternate solution "code-prettify" which is much simpler and easy to integrate.

Step 1 - Just include the library & you are done with its setup
Just include below script in your blog / website before closing of head tag. Once it's done you can simply make use of tag to highlight your code. Check the sample code explained in step 2 to learn how to use this script.
<script src=""></script>

Step 2 - Copy the code block in PRE tag with mentioned class
It's very simple to use, you simply have to use PRE tag and give it a class "prettyprint". We also need to specify the second CSS class for script to understand which programming language colour formatting pattern to use. In below example I have used class "lang-html". This will notify script that my code block needs HTML formatting.
<pre class="prettyprint lang-html">
      Your code block here
Highlighting PHP code
<pre class="prettyprint lang-PHP">
 echo "Hello Friends";
Highlighting JavaSctipt code
<pre class="prettyprint lang-javascript">
  var DM = 'Hello friends';
Note - It works perfectly with many other languages, please check their github link for more details.

HTML5 Way to do the same
If you wish to use standard HTML5 elements to highlight your code then you can use following code block.
<pre class="prettyprint"><code class="language-python">
class Employee:
    def __init__(self, name): = name

    def outputName(self):
     print "Name = %d" %

Sunday, January 15, 2017

Sample code to add tooltip to d3js chart

Last few weeks I have been writing the posts related to data visualisations using D3.js charting library. Initially I have shared the sample code to explain simple line chart. My previous post was about adding the grid lines to chart and in this post I want to help you all with an example of adding tooltips to our chart points.

Sample code to add tooltip to your charts

While working on charts, some time we come across the situations where we need to show data on mouseover event. Let's consider an example when we need to show x & y axis values of the data point on mouseover. In such situations adding a tooltip to chart points is best way to show such type of data. I usually create an empty DIV with class as tooltip and append it to the body. Then we need an event to unhide this DIV. In D3.js we can use "mouseover" event of the chart point to unhide the tooltip. Following is the sample code which you can use directly to show the tooltip on your chart. Lets learn with the following example.

Step 1 - Append an empty DIV to body
// Define the div for the tooltip
var tooltipDiv ="body").append("div") 
    .attr("class", "tooltip");
In above code we are adding an empty DIV to the body and giving it a class "tooltip" with attr method.

Step 2 - Apply style to the tooltip DIV
div.tooltip { 
    position: absolute;   
    text-align: center;   
    padding: 10px; 
    font: 12px sans-serif;  
    border-radius: 8px;   
    pointer-events: none;   
You can use your styling here to design skin of your tootltip element.

Step 3 - configure mouseover and mouseout events to hide/unhide tooltip
.on("mouseover", function(d) {  
// code block for tooltip
    .style("opacity", .9);  
tooltipDiv.html(d.year + ' : ' + 
    .style("background", pointColor)  
    .style("left", (d3.event.pageX) - 30 + "px")  
    .style("top", (d3.event.pageY - 40) + "px"); 
.on("mouseout", function(d) {  

    .style("opacity", 0); 
This is last and most important step, we simply have to write a code to hide the tooltip on mouseover event and hide it on mouseout event. You have to write this code block while preparing the points on the chart. If you are confuse about how to place this code then please check the above demo link and check the working example.

Next > Highlight data points on mouseover