Flipboard Like UI on iPhone Safari ( JavaScript + CSS3)

I was trying to make Flipboard like UI in CSS3 and JavaScript!! I quickly made it to work on chrome, but it sucked on iPhone, and it took ages for me to make it work.

How I made it?

My approach is simple I used basic CSS3 attribute

-webkit-transform: rotateX(180deg);
-webkit-transition-duration: 2s;

To achieve complete flip of a page you need to add CSS style of -webkit-transform: rotateX(180deg);

Problem with 180 flip is your HTML content goes upside down, to simulate flipboard like animation you can not flip it complete 180 degrees

Then i decided to just flip 90 degree and back to zero degree Demo-1, To fake half page flip i added a mask on it so that one half of animation is not visible Demo-2.

With this concept of mine I went ahead and made full page flip demo for iPhone here Demo-3.

Scan to see demo on iPhone

Problems on iPhone's Safari

1) z-order problem on webkit, with 3D transform
This mask thing could not work properly because In  iPhone's safari when a object is  3D transformed , z-order does not work properly.  I worked around it by making one half of page to transparent.

2) Touch Events of iPhone
Touch events on iPhone have some serious problem, i encountered weird problem with event propagation.

Feel free to ask any question about the Demo, Please let me know if You have better solution to emulate Flipboard UI.

Curl Request with custom IP and hostname (in php)

There could be following instances you might encounter while doing curl!

  1. If host-name used in RequestURL, is not in public domain.
  2. If you are trying to avoid load balancer routing, while curling to a local domain. 
  3. If single server serves multiple hostnames, and hostnames are not yet registered. 
Here is what you have to do!!
  1. Curl with url by IP-Address. (that might return 400 error if server is serving multiple domain.)
  2. To solve this include host in HTTP header. 
How To do it?


$session = curl_init('http://'.$ipaddress.$url);
$headers = array("Host: ".$http_host);     
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
curl_setopt($session, CURLOPT_TIMEOUT, $timeout);
$content = curl_exec($session);
echo $content

This how to get local ip and hostname in php

In command line curl 
 curl "" -H "Host: myhostname.com"

jQuery plugin to fix color contrast ratio between background and foreground

There might me scenario when you are fetching  html snippet from external source, what if color specified in the external html is not working on your page due to different background foreground definitions. is there jQuery Plugin exists which can fix contrast ratio so that text is still readable?

Yes this is jQuery plugin which automatically analyses the contrast ratio between foreground and background and corrects automatically to make it readable.

Its very simple to use. include  javascript from here and call function fixColors.

<script src="http://www.purplegene.com/js/fixColors.js">

Core logic of this code exists in function getColorInfo which returns various information about any color, like brightness of color and maximum color contrasting color, etc.

function getColorInfo(strColor){
        //regEx to parse rgb(10,10,10)
        var match=strColor.match(/rgba[ \t]*\([ \t]*([0-9.]+)[ \t]*,[ \t]*([0-9.]+)[ \t]*,[ \t]*([0-9.]+)[ \t]*,[ \t]*([0-9.]+)[ \t]*\)/);
        var isAlpha=true;
            match=strColor.match(/rgb[ \t]*\([ \t]*([0-9.]+)[ \t]*,[ \t]*([0-9.]+)[ \t]*,[ \t]*([0-9.]+)[ \t]*\)/);
        var r = match[1]*1, g = match[2]*1,b = match[3]*1, a = match[4]*1;
        var brightness = (r * 299 + g * 587 + b * 114) / 1000, cb = 20;
        if (brightness < 127) {
            cb = 235;
        var rgbOnly='rgb('+r+','+g+','+b+')';
        var maxContrast = "rgb(" + cb+"," +cb+"," +cb+")";
        return {'r':r,'g':g,'b':b,'a':a,  

This is how to fake Siri on chrome

When Apple declared Siri , everyone knew that siri is not magical,  all technology involved in siri is already present. Here is how you can make your own.

Voice Recognition
Voice input is a proposed HTML5 feature by Google. Its already experimentally available in latest versions of chrome.
<input id="speech" type="text" x-webkit-speech onspeechchange="startSearch">

Intelligence with Wolfram Alpha
Wolfram Alpha is one of the most awesome search engine (or Computational Knowledge Engine in their terms). They have open API to make your own app.

Recently chrome brought up the tts support in its chrome extension, which can be used to give voice to you Siri hack. 
    function() {
      if (chrome.extension.lastError) {
        console.log('Error: ' + chrome.extension.lastError.message);

Simple two (or multi) column layout that works

Hi There!

2 Column layout is very painful does not work often. Here is a very simple 2 colum layout that works.

  overflow: hidden;
    content: "\0020";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
<div class="grid">
      <div class="left">
   Left Stuff Goes Here 
      <div class="right">
   Right Stuff Goes Here 
To make 3 or more column layout follow the same strategy , just distribute the width of children (e.g. left and right) and keep adding them, all the children will float left and last child will float right. Such multicolumn layout can be well nested to achieve complex grids .

Design of cross domain POST API in Javascript

Hi There,

As all of you know that cross domain POST is not allowed in javascript. At Times few APIs require you to do POST, such APIs are extremely hard to use in pure javascript mashups. We can not move back to GET method because the input set is limited ( restricted by length of URL) on GET.  So in this article I am proposing a design of POST API which will be javascript friendly.

Lets say I am designing a API which requires "text"  as input in POST, and returns an JSON response.

                 API URL: http://api.xyz.com/myapi 
                 API Input:  text as POST field.
                 API Output: JSON object.

1) How client can invoke the API?
 of-course cross domain HTTPXMLrequest is not allowed
Another popular technique of  injecting script tag with callback to get cross domain JSON (jsonp) can not be used becuase it can only do GET request. so how to do a POST to differnet domain? Solution is you can use iframes.
  1. Create an iframe in javascript
  2. Create a form whose method is POST, action is API URL and target is the iframe.
  3. Create hidden input as "text" and assigned the value whatever you want.
  4. Submitted the form.

Here is the code

function crossDomainPost(url, text) {
    // Add the iframe with a unique name
    var iframe = document.createElement("iframe");
    var uniqueNameOfFrame = "sum";
    iframe.style.display = "none";
    iframe.contentWindow.name = uniqueNameOfFrame;

    // construct a form with hidden inputs, targeting the iframe
    var form = document.createElement("form");
    form.target = uniqueNameOfFrame;
    form.action = url;
    form.method = "POST";

    // repeat for each parameter
    var input = document.createElement("input");
    input.type = "hidden";
    input.name = "text";
    input.value = text;


2) How to read the output back?
Now since form is submitted in iframe, whatever is happening in iframe is not accesible to main window and vise versa due to cross origin restrictions imposed by browsers. So this is where you should follow my proposed design,
The API maker will return an HTML page with script block in it. Script block should send a message (HTML5 cross frame messaging API) to parent frame.
e. g. Output of API  goes like this.
var json={your-data}

This is how client will read in his javascript code
window.addEventListener("message", function (event) {
}, false);

Note: message posted is HTML5 API may not be available in many browsers. 

Thanks and enjoy!!!!!


As you know that Steve Jobs is no more with us
 To to express your  condolences please change your DP to this photo (Next 5 days...)
Thanks, and share this message!!!! 

How complex is to remove javascript from HTML? (to prevent XSS)

There are few situations where you want your users to enter plain HTML but you do not want them to execute javascript. Problem seems very simple but its very complex.

In this article I will let you know the complexity of doing this rather proposing any solution.

Lets start with the ways javascript can appear in an HTML document. Here are few things  I am listing.

1. In script tag
javascript typically appears in an script tag e.g

<script src="http://www.someurl.com">


alert('hi javascript')

2. In event attributes

Next simple way in which javascript can appear in your HTML is as event handler.

<div onclick="alert('hi javascript')">

Though w3c document describes following attributes as intrinsic events but depending on browser implementation it might change

    onerror <-- img onerror event

3. In anchor href

<a href="javascript:alert('hi javascript')">Click Me</a>

4.  In href and src tag of some media tags

In some of the older browsers (e.g. IE6) img src tag can contain javascript.

<img src="javascript:alert('hi javascript')"/>

this situation might also appear in various ways as

<TABLE background="javascript:alert('hi')" or 

<LINK REL="stylesheet" href="javascript:alert('hi');">
<BGSOUND SRC="javascript:alert('hi javascript');">

5. In CSS attributes 

 background: #28d expression("alert('hi javascript')");

this can appear in any place where CSS can appear i.e. external CSS, style block or inline style attribute.

6. base64 encoded svg can contain script tag

<EMBED SRC="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==" type="image/svg+xml" AllowScriptAccess="always"></EMBED> 

7. Encoded Scenario of any of the above case. 

Any of the above case may or may appear as encoded format e.g.
<a href="javascript:alert('hi javascript');">
is same as
<a href="&#x6A;&#x61;&#x76;&#x61;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x3A;&#x61;&#x6C;&#x65;&#x72;&#x74;&#x28;&#x27;&#x68;&#x69;&#x20;&#x6A;&#x61;&#x76;&#x61;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x27;&#x29;&#x3B;">

Important Note: 
1) code might appear in upper case or lower are e.g "javascript:" can be writtent as JaVaScript:

2) <script> tag can appear as multiline

3) since html attribute values may or may not be wrapped under quotes
url like http://www.yahoo.com+ onmouseover ="alert('hi')" might generate code like this
<a href=http://www.yahoo.com onmouseover="alert('hi')"/>  which is wrong!!!!!!!!!

4) Usefull Links

How to get user location in javascript (YUI)

Hey Guys ,
Here is a simple code to get User's Location (lat and lan) in javascript using YUI.

Why Not to use HTML5?
Html5 is not yet supported by many browsers and have no fall back. YUI implementation falls back up to ip based location.

<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Location using YUI (with fallback)</title>
<script src="http://yui.yahooapis.com/3.4.0pr3/build/yui/yui-min.js"></script>
YUI({gallery: 'gallery-2011.05.12-13-26'}).use('gallery-geo', function(Y) {
if (response.success){
var e=document.getElementById('geolocation');
e.innerHTML="Your Location :"+response.coords.latitude+","+response.coords.longitude;
<div id="geolocation" >


Note: If you host the file locally, e.g. file:// , it might not work due to security issues. 

How to play youtube video in loop ???

Its very simple!

1) Click on "watch later" button to add the video in "watch later" playlist.
2) Play this playlist.
3) select autoplay option (remove other videos from the list if you want)

congratulation you just created a loop.

Here is Video Demo, how to do that

Yahoo! Open Hack India is Here

Hi ,
India's most awesome developer event 'Yahoo Open Hack Day' is back.  Here is few tips if you are planning to attend.

Text Editors
On HackDay you need to come up with the hack in just 24 hours of time, Which is short time, so make yourself ready with right tools.
If you already have your favorite text editors make sure that they are  javascript/HTML/CSS ready. If you Do not have one I will recommend you to use Komodo Edit (on all platforms). Komodo has built-in support for web languages like HTML, Javascript and CSS.  I will strongly recommend you to use Komodo but you have some more options here
Notepad++( for windows).
Textmate on Mac is fair deal.
Vi (try installing snipmate and other useful vi plugins)

Brush up on Javascript HTML and CSS
Though your are free to hack in any language possible, I will recommend you to learn javascript(CSS and & HTML). Yahoo hack day is the best place to get your hands dirty on these languages. Javascript is most popular language in the world already and it spreading on all possible computing device.  So better you make up your mind to learn them. Era of things like GWT and ASP.net (where you bypass these languages to get the things done) is Over.
Watch this video to know how to start writing and executing javascript. Here is awesome video to know deeper in javascript. This is from Doug Crockford, based on his book "Javascript Good parts" available for Kindle. (do you know kindle is available for PC?).

YQL / YUI3 / jQuery
YQL is best things ever invented after AJAX and JSON. YQL has tables for almost  all popular ajax/REST APIs on web. Just spend a lil bit of time to understand YQL and I will promise you will have easy time on hack day.
YQL is awesome for doing page scraping. You can also try my hack.

YUI3 is very professional javascript library to work with, but since this is going to be a hack-day, i will personally recommend you to use jQuery for quick win.

Web Browser (+firebug)
firefox (with firebug/Yslow plugin) is very popular browser among web developers. You can use chrome as well. The whole idea behind having firebug is you will be able to debug your code right in the browser. Chrome developer tool is not bad,  you can watch this video to get familiar about it.

Other things
Get a  Camera, there will several moments to capture.
Do not bring any food , you will get hell lot of that right at the venue.
I have quite a few of hacks posted on my blog they will be a good example of how to quickly create a hack , but they are not winning hacks ;)

3 Things to fix window management on Mac (for Windows-7 users)

Hey Guys,
I recently switched to mac (Snow Leopard) from windows7. Window management on Windows has been always good compare to the mac, except the feature like expose which is missing on Windows for long time.

When you switch on mac  you might miss couple of feature related to window management. Here is few things you need to fix.

1) Capability to maximize windows 
Window maximizing on Mac sucks, when you maximize it, window will just increase its height to fill the screen and width will remain same. Windows users are definitely not use to this, so to fix this you need a application called RightZoom.  It will simply fix the default behavior of green button. RightZoom is free.
2) Aero Snap
Window snapping on the edges was an awesome feature added in windows7. It made the life real easy when you trying to keep 2 windows side by side. Though exact feature is not available on mac via various paid utilities but the ShiftIt Is good enough to bring kind of similar experience on mac and its free.

3) Capability to Go Fullscreen
Most of the application on mac don't go fullscreen,    I seriously hate this, To fix this problem You can use MegaZoomer, Which will introduce a shortcut to go full screen in most of the application. This is application is also free. Megazoomer is SIMBL plugin, download and install SIMBL first and then copy the Megazoomer in the plug in directory. You might have to restart the machine after installation.

Download MegaZoomer

Thanks for reading !

Online XSLT Editor

Hey Guys,
I just created an XSLT Editor. Its very useful for writing quick XSLT for XML you have in hand.
As soon as you type XSLT code you will see the preview in output window in real time.

I hope this will be useful for you guys. Feel free to share!

Here is the direct link

What it takes to make your own RSS Feed Reader in HTML5?

Before I tell you the list of all the APIs and Resources that I used to make my feed reader, jump to this page (use Chrome) to get a Demo of what I have created.
PurpleGene Feed Reader is a HTML5 (offline) web application for feed reading. No user-name & password required to use this feed reader.

Here is the list of all resources you need to build something like this one.

1) Doctype:
Any html5 page should be having a html5 dock-type. dock-type declaration will make all the browser to switch into html5 mode and they will render your page as per the new standard.
html5's doctype declaration is like this
2)Cache-Manifest :
In HTML5 Cache-Manifest is a way to declare the list of resources that should be cached to run the application offline.
This file lists all the resources like images and JavaScript required to run your page. cache-manifest is a page linked through your app's main html code.

Here is how my webpage has linked its cache manifest
<html manifest="cache-manifest-reader?version=1.0"> 
Note that URL /cache-manifest should be served with correct MIME type. Which is  'text/cache-manifest'.
To know more details about cache-manifest, go here

Real life example of cache-manifest is here(my FeedReader) http://www.purplegene.com/cache-manifest-reader

3)Google's Feed API 
Feed API is not HTML5 Feature. I am using Google's AJAX Feed API to gather feeds.

A quick code example of Google' Feed API is here

4)Google's Web Fonts (CSS3 web-fonts)
CSS3 supports web fonts, luckily Google hosts many awesome fonts online for you.
Here is google's font directory http://code.google.com/webfonts
To use any font you just have to include the fontface declaration in your page using google's web fonts API'

<link href="http://fonts.googleapis.com/css?family=Goudy+Bookletter+1911" rel="stylesheet" type="text/css"></link>

And then simply use it in your CSS
h1 { 
font-family: 'Goudy Bookletter 1911', arial, serif; 

For me its very hard to continue any javascript development without using jquery, jquery simply makes your life easier while manipulating the DOM. I am using jquery for keyboard shortcuts ,all DOM manipulations & animation.

7)HTML5 Local storage 
HTML5 local-storage API is awesome!! Using this you can save any data (from JSON) to local persistent store with a very simple javascript calls

  function GetOfflineData(ItemName) {
       return JSON.parse(window.localStorage.getItem(ItemName));

  function SetOfflineData(JsonData,ItemName) {
       window.localStorage.setItem(ItemName, JSON.stringify(JsonData));

Pit Fall (circular json object)
Note that at any point of time if your JSON will go cyclic then JSON.stringify function will fail to do that.
here is example of cyclic JSON

var json={"hello":"{"test1":1}}

so solution to the problem is either you don't use something like that, or pass a function as second argument to the stringify function to let it know that parent member should be avoided.
like this

JSON.stringify(json, function(prop, val) {
                return ((prop === 'parent') ? undefined : val);

8)bitly APIs for link shortening (twitter sharing)
 bitly has a very clean REST API for link shortening, here is a example to shorten a link.
function TryShorteningLink(longlink) {
        try {
            var login = Configuration.Configuration.bitly.user;
            var key = Configuration.Configuration.bitly.key;
            var url = 'http://api.bit.ly/v3/shorten?login=' + login + '&apiKey=' + key + '&longUrl=' + escape(longlink) + '&format=json&callback=?';
            $.getJSON(url, function(result) {
                if (result.status_code === 200) {
                    alert('link is shoten now!!'+ result.data.url)
        catch (err) {}
I am terrible designer, I know that if i will try to make something colorful i will mess the things up. So i always stick to minimalistic approach , To designs the icons i just used character written on a blue circle. To make it looks little better that circle has minimal gradient.
I used this svg editor to create them, then exported to PNG format.

10)Configuration Editor
Since most of your offline data will be stored in JSON , it was much better idea to expose the JSON editor itself for configuration editing. If you look at the configuration panel , you will see a nice JSON editor, this editor is created by me and you can get that from here.

11)  CSS3 Column

The SneakPeek View of my Feed Reader uses CSS3 columns (This is not yet supported by Opera and IE9)

div#multicolumn1 {

-moz-column-count: 3;
-moz-column-gap: 20px;
-webkit-column-count: 3;
-webkit-column-gap: 20px;
column-count: 3;
column-gap: 20px;

Thanks for reading

JSON Editor Using YUI TreeView

Hey Guys,

I have created a JSON Editor, using YUI TreeView.
Its very simple to Use!

All functionality is wrapped in jsonEditor.js , which is tiny JavaScript library,which can be used for making your own JSON editor.

This library is simple to use.  Here is what you need to do.

Create a div with some ID lets say treeView and then a create text-area with id as "textEdit".
Pass this 2 parameter in jsonEditor constructor, Thats it You are done!
Here is sample code

/*Do This on Dom ready*/
je=new jsonEditor('textEdit','treeView');

This Uses YUI & jQuery so make sure you are including these libraries in your page.

Here are all dependencies, put these in head part of HTML:

<link rel="stylesheet" href="http://yui.yahooapis.com/2.8.0r4/build/reset-fonts-grids/reset-fonts-grids.css" type="text/css">
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/fonts/fonts-min.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/treeview/assets/skins/sam/treeview.css" />
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/treeview/treeview-min.js"></script>
<script type="text/javascript" src="http://www.purplegene.com/js/jsonEditor.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.4.2");

Here is screenshot

Note:  This is Only Tested in Firefox and chrome. Use at your own risk! Do not hotlink my js file.

Which browser is faster as of now?? (DOM+JavaScript)

Hi Guys,
When it comes to performance of Browsers its not just JavaScript. Speed of DOM plays very important role in the performance.
Today I have quickly written small test function to Test JavaScript+DOM performance on all major browsers.


So here I have the test code

Faster and Better way to embed code on blog

If your blog posts often contain some code snippet then read this post.
While embedding code on your blog, you might have felt these problems

1)Syntax highlighting
2)Escaping (i.e.  if ur code contains html then you need to escape your code)
3)Code editing & Versioning (i.e.  Once you got the escaped & highlighted code, editing becomes tough)

All these problems will be solved if you host all your code snippet on GitHub as Gist 

Solution is: use GitHub Gist!!
As most of you already be knowing that GitHub is a web-based code hosting service that uses the Git revision control system. GitHub has a feature called Gist where you can store (and version it) small code snippet without actually going through any git problems.
You can version edit and host your code as Gist, additionally you can embed this code on your blog which comes with syntax highlighting and character escaping for free!

One Problem Though!!!
Github Gist embedding comes as script tag (which loads your Code).
Problem with putting such code in middle of the blog post is, When user loads your page, entire page loading will be blocked until this script is loaded .i.e. Your blog page will load slower!!

So how to keep it faster?
Typically to solve this problem people use script tag injection in DOM using some light weight script. This method will not work here because GitHub Gist embed method uses document.write to bring the content inline.

Other simple solution is Use iframe, I have created a small web handler on PurpleGene.com to embed this code and then you can include this page as iframe. note that iframes load in parallel.

Here is How
suppose you have a gist like this

Then embed code will be
<script src="https://gist.github.com/764648.js?file=Qompress.cs"></script>
Now If you want to embed this code just
1)Replace script tag with iFrame
2)Append URL http://www.purplegene.com/script?url= in src field
3)Beatify by giving attribute as width="100%" height="300" or what ever you want.
Your final code will be
<iframe width="100%" height="300" src="http://www.purplegene.com/script?url=https://gist.github.com/764648.js?file=Qompress.cs"><br />
Thats it Have fun!!!!!!


PurpleGene.com is owned by me, so assume it to be safe, if do not trust me then you can simply go ahead and create a small app on appengine for free and use it!

Compress and Decompress in C#.net

Hi Guys,
Just wanted to share a very simple code example to compress and decompress in c#.net.

Here it goes.

From File????
If you are trying to compress and de-compress a file then use this to read into a file.

To Read from File
byte[] rawData = File.ReadAllBytes(FileName);
To Write to a File

Have Fun