Css Tip – Css Browser Selector

Styling sites for different browsers have always been a headache for front end developers. Sometimes, the implementation has its own prefixes, sometimes the model doesn’t work at all.

Browser specific stylesheets

So developers came up with the idea of browser specific stylesheets. For each different browser, you redefine a few style declarations to make the layout and styling work.

But having multiple stylesheets is far from optimal. You take more effort to organize your files, some browsers have quirks that needs some fixing, and all sorts of weird problem pops up. And that adds up to a lot of time wasted.


One more elegant solution will be to borrow the idea of browser prefixing. Instead of having multiple stylesheets, you now have one stylesheet with all the fixes that you can apply.

Even better, using this method allows you to extract other details like browser versions and operating systems. This way, you can target differrent content at different platforms and still have a static one-page website.

How it works

This is a script from Rafael Lima. The basic idea is to extract information from the userAgent string and apply the appropriate classes to the document element.

And when defining the style declarations, you just have to use the appropriate classes to fix the different cross browser errors.

Access the script from here


This way of frontend development focuses on limiting server side interaction. Sending all the information to the client and let all the decision to be done over the client side.

All methods have their pros and cons. This method will be suitable for simple sites that require simple static content. If you are working on a site with dynamic content, handling the browser fixes server-side could be an appropriate choice, since its just a simple extension and can help reduce page load time.

If there is any questions or queries, leave a comment or drop me an email.


Introducing tumblr pbot

Journaling can be difficult sometimes, you need to have your book with you, you are not sure where to start, you get distracted. These are problems faced by many of us.

Tumblr pBot helps you get started on your journaling in as little steps as possible. Just start typing and send it, and up or goes onto tumblr.

Want a private journal, no problem, just make your tumblr page private, and nobody will be able to access your private thoughts.

Want to review your entries? Since everything is uploaded onto tumblr, you can make use of tumblr post management system to review and read through all your entries.

Want to categorize your entries? Use tags. Tumblr’s tagging system is supported in the pBot. Simply add in the tags at the end of your posts and it will be immediately uploaded with tags attached.

Don’t know how to start? Even better. Using telecom’s text messaging interface makes it feels like you are typing to a friend, making it easier to pour out all you have to say.

Getting distracted from writing? pBot is as minimal as it gets, you can now focus on what you are writing. Since its so accessible, you can get in, pour out your thoughts, and get back to whatever you are doing.

Try it out now. Or visit the bot page.

Tutorial – Making a game in SVG


One of chrome’s best easter egg is the offline side scroller dino game. In this tutorial, I will be teaching you how to recreate a simplified version of it in SVG.

For this project, we will be using handlebars library to draw updates to the screen as it scrolls along.

note: the javascript in this tutorial is incomplete (i.e. each section only contains the relevant parts). To view the full code, visit the codepen.

Setting up the canvas

For a start, we will setup the code to render the SVG. We will only display the ground and the dino for now.

Every game will have a update loop to make the necessary movements and redraw the display. Our update loop will contain the code to render the game’s SVG figure.

This update loop is usually accompanied with a fps variable, indicating how long apart each update function call is.

// gid is shortcut for document.getElementById
var template = Handlebars.compile(gid('template').innerHTML);
var base = 280;
var fps = 20;

var data = {

function update(){
  gid('game').innerHTML = template(data);

The handlebars template for generating the game contains only the background, floor and the dino, as of now.

<svg viewBox="0 0 800 400">



  font-family: Helvetica, Arial, Sans-serif;
  font-size: 40px;


  <rect id="bg" x="0" y="0" width="800" height="400"></rect>
  <rect id="ground" x="0" y="380" width="800" height="20" fill="#FF0"></rect>
  <rect id="dino" x="80" y="{{dino_y}}" width="80" height="100"></rect>

Making the dino jump

Implementation To receive the clicks, we will have an overlay that will spread across the screen.

The jump function is really simple, there will be 3 main variables for this function, dino_y, dino_dy, and env_g.

The first variable, dino_y stores the current y coordinates of the player. dino_dy represents the vertical speed, positive for moving upwards, negative for moving downwards. env_g is gravity. Using these 3 variables, and some simple physics, we can make the dino jump.

Here, we will be making good use of the fps variable. Each variable change will be in terms of 1 seconds, so the fps will be used to add increments of the change during each update.

var data = {
  // ...

  /* main 3 variables for jumping calculation */

function jump(){
  /* only one jump at a time */
    data.dino_dy = data.dino_jump;
    data.dino_flr = false;

function update(){  
  /* change in speed and position */
  data.dino_dy -= data.env_g/fps;
  data.dino_y -= data.dino_dy/fps;

    data.dino_y = base;
    data.dino_flr = true;

  // ...

For each update loop, an increment of x/fps is added. After 1 second, the full value x will be eventually added.

Creating obstacles

In the game, there are all these different different obstacles that will be created on the fly. This part will show you a method of generating the obstacles.

There will be 3 classes of obstacles, small, medium and large, correponding to the different obstaclesin the original game, spike, small and large cactus.

For each set of obstacles (cactus or spikes), we will have a random distance between them (between 500px to 1200px).

Then depending on the type of obstacles, there will be different number of it in each set. There will always be 3 spkies, 2 to 3 small cactus, and 1 to 2 large cactus in our game.

Of course, we will have to animate the obstacles too. For that we will have the env_dx variable to set the speed of the obstacles, which will be used in the update loop to move the obstacles along.

var data = {
  // ...
  objs: []

function createObjs(){
  /* staring generating from x=80 */
  var last = 80;
  var objs = data.objs;

  /* get x position of the last obstacle */
    last = objs[objs.length-1]['x'];

  /* dunnid to generate until too far */
  if(last>1200){ return; }

    last += rand(5,12)*100;

    /* option of spike, small or large cactus */
    var opt = rand(2);
    var h = [50,100,150][opt];
    var w = [50,50,60][opt];

    /* random count of the obstacles in each set */
    var c = rand([3,1,1][opt],[4,3,2][opt]);
    for(var i=0; i<c; i++){

function update(){
  /* moving existing obstacles */
  for(x in data.objs){
    data.objs[x]['x'] -= data.env_dx/fps;
    if(data.objs[x]['x'] < -500){ delete data.objs[x]; }


In the update loop, the createObjs function is called to replenish the obstacles after the past spikes and cacti have long moved off the screen, thus creating an “infinite level”.

Setting the score

For the original dino game, the score is depedent on how long you survive in the game. We will thus have another timeout just to increment the score, 10 points per second of surviving.

function score(){
  data.env_s += 1;
  window.to_score = setTimeout(score,100);

Colliding with the dino

Since all the objects in the game are rectangles, we can use the simple boundary box collision test.

figure for collision test

The brief idea is that the x-axis segments of the 2 bounding boxes cannot collide, same goes to the corresponding y-axis segments.

function collide(obj){
  /* player's bounding box boundary */
  var dino = {
    y2:data.dino_y + 100

  /* object's bounding box boundary */
  var wall = {
    x2:obj.x + obj.w,
    y1:380 - obj.h

  /* simple rect obj collision */
  if(wall.x1<dino.x2 && wall.x2>dino.x1 && wall.y1<dino.y2 && wall.y2>dino.y1){
    return true;

  return false;

function update(){
  for(x in data.objs){
    if(!x){ continue;}

    /* only check if the obstacle is close enough */
        // we will handle this in more detail later

The collide function takes in the information of an obstacle, gets its extreme boundaries and compares it with the player’s extreme boundaries. If there is a collision, the function will return true.

Reseting the game

Time for some refactoring. To create a game that can be started and restarted over and over again, we will wrap all the initialization and the start of the update loop into a reset function.

Along with it, we should have a function to end the update loop, this will be aptly named lost. The will contain all the code for removing the timeouts and resetting the score.

function reset(){
  window.data = {


function lost(){
  /* can add other stuff if you want */

function update(){
  /* collision */
  for(x in data.objs){
    if(!x){ continue; }



Making it harder

There are a many improvements you can make to make the game more challenging. Here are some ideas:

  • Increase speed at higher scores
  • Increase gravity so player drop faster
  • Reduce distance between obstacles to reduce time for reaction
  • Increase the number of obstacles per set, making the obstacle set longer

As for the code, I will leave it out as an implementation exercise. Have fun!


Tutorial – SVG Rendering with Handlebars


Handlebars is a javascript templating library that can be used to generate content on the fly. SVG (or scalable vector graphics) generates graphics from xml. In this tutorial, we are going to generate a figure (a SVG) to show the addition process of two two digit numbers.

SVG figure design

To align the numbers, we are going to split the numbers into their inidividual digits and then render them separately. Each digit will fit inside a 40 by 40 pixel square. And the “carry over marking” at the top, will fit inside a 20 by 20 pixel square.

The labelling of the numbers are as follows, the first row numbers start with a, so the tens place of the first number will be aa and the ones placing be ab. The tens place of the second number is ba and ones place bb. Similiar, hundreds, tens, and ones place of the answer will be ca, cb, and cc respectively.

<svg viewport='0 0 120 180' width='120' height='180'>
    <line x1="0" y1="110" x2="120" y2="110"></line>
    <text id="numbers">
        <tspan id="aa" x="50" y="60">{{aa}}</tspan>
        <tspan id="ab" x="90" y="60">{{ab}}</tspan>

        <tspan x="10" y="100">+</tspan>
        <tspan id="ba" x="50" y="100">{{ba}}</tspan>
        <tspan id="bb" x="90" y="100">{{bb}}</tspan>

        <tspan id="ca" x="10" y="160">{{ca}}</tspan>
        <tspan id="cb" x="50" y="160">{{cb}}</tspan>
        <tspan id="cc" x="90" y="160">{{cc}}</tspan>
    <text id="marker" x="30" y="30">{{m}}</text>

Generating the text for the diagram

There will be a form for us to get the two numbers, the first input will be id-ed a, the second input will be id-ed b. Then the button of course. The figure div will contain the final rendered SVG.

In the script, we first get the two numbers, add them up together, check whether the value will carry over. Then transform them to string, after that we will render the SVG.

function update(){
  /* shortcut functions */
  var $ = function(qry){
    return document.querySelector(qry);  
  var _ = function(txt){
    return parseInt(txt);

  /* getting the values */
  var a = $('#a').value;
  var b = $('#b').value;
  var c = (_(a) + _(b)).toString();

  /* transforming to text */
  var res = {};

  if(a.length>1){res.aa = a[0];}
  res.ab = a[a.length-1];

  if(b.length>1){res.ba = b[0];}
  res.bb = b[b.length-1];

  if(c.length>2){res.ca = c[0];}
  if(c.length>1){res.cb = c[c.length-2];}
  res.cc = c[c.length-1];

  /* the carry over marker */
  res.m = (_(res.ab)+_(res.bb)>9) ? '1' : '';

  return res;

After getting the values, we will render the SVG using handlebars library. And put the value into the #figure div.

var template = Handlebars.compile($('#template').innerHTML);
$('#figure').innerHTML = template(res);

Final product

When you put everything together, you have this. There you have it, handlebars rendering of a SVG figure.

Getting Started 2: html – markup language for web documents

This is the 2nd post in the Getting Started series.

Basic HTML

HTML(hyper text markup language) is a data representation format based on XML. It is used for formatting web documents in general, and contain all the required elements for a browser to render the tags as a website.

Basic XML

HTML(or XML in general) follows this following set of formatting and rules.

Sample XML Document (Not HTML btw)

    <title>Hello World Page</title>
    <article author="Metta Ong">Lorem Ipsum</article>

As seen from above, the document is formed by tags in the form of tags. Tags come in pairs, opening and closing tags. The opening tag is enclosed with a less than and greater than sign, and a closing tag has a / before the tag name.

Attributes are “descriptions” attached to the tags. In the above example, the author="Metta Ong" is the attribute attached to the article tag. Content placed between the open and close tags are actual text content of the tags.

XML hierachy is pretty simple to understand. In the example above, both the title and article tags are considered children of the Document root tag.

Main structure of web pages


Main structure of web document

Different versions of HTML

There are many HTML versions out there (the most recent one is HTML5). To tell the browser which version of HTML your document is, we use the DOCTYPE tag.

So, at the top of your document, incude the following line: “. This tells the browser that your document follows the HTML5 format.

For those curious few out there, there are a few different types of DOCTYPE for HTML4 document is – strict(), transitional(), etc. You can read more about doctypes here.

Main 2 components

The head tag is the place where all the information goes. Data contained in this tag is usually not rendered. By convention, all scripts and styling goes here, together with all the information of the document, like the title, description, etc.

The body tag is the place where all the rendered information go. All your headers, navigation and content goes here.

Document information

    <title>Title of Document</title>
    <link href='/path/to/stylesheet.css' type='stylesheet' />

Example head tag

All the information will be stored here, the title of the document, all the metadata (description, author, etc). The metadata can be used for search engine optimization (SEO), it gives the browser detailed information to categorize your document (more on that in other tutorial).

While styling can be done on the main html file itself, you can also attach stylesheets using the link tag. The syntax to do so is as follows: “

You can attach things like favicons (the small tiny logos for your page). Using the link tags, these images can be attached as so:

<!-- linking a style sheet -->
<link href='path/to/style.css' rel='stylesheet' />

<!-- favicon -->
<link href='path/to/icon.png' rel='icon' type='image/png' />

Basic components

In the previous post, you learnt about formatting documents using markdown, know that you know the basics about document formatting, I will now teach you how to do all that in HTML (yeah, finally :>)


In markdown, there are different kinds of headers, representing different layers of information. The highest level of all headers have the h1 tag, it all goes all the way, from h2, h3, all the way to h6.

<h1>Usually for the main title of the page.</h1>
<h2>Subheadings. Title for the different sections</h2>
<h3>Even smaller headings, content headers maybe?</h3>
<h4>Not too sure why you would go so deep...</h4>
<h5>Probably just use this for styling purposes...</h5>
<h6>When you reach here, its time to split your content...</h6>

Paragraph text

The p tag (yeah, p for paragraph) used to contain all your text. It can be can be any kind of text, its the generic text container. It is to be embedded in the new HTML5 content tags for SEO (searc engine optimization).

Text styling

Within the paragraph tags, there are some special styling tags to basic transformation to yout text. Here are some of the basic tags available for use.

<b>bold, b for bold</b>
<strong>makes the text bold</strong>

<i>italics effect, i for italics</i>
<em>also italics effect, emphasized</em>

<u>underlined text, u for underline</u>

<mark>highlight text. yep, like a highlighter.</mark>

<s>to show cancellalation (strikethrough), really...</s>
<del>strikethough, similar to the 's' tag</del>

<sub>subscript, text written close to the foot of the text</sub>
<sup>superscript, you know like in math, the power function</sup>

<code>Shows code. text will be displayed in monotype font.</code>

For more advanced styling, you can take a look at the CSS declaration specified for text..


Your pages will be boring with any visual candy. The image tags (img) contains your images. (like duh.)

<img src='http://lorempixel.com/400/200/' alt='a random image' />

Yes, img tags are one of those special kinds that do not need to be closed (because your browser most likely wont render anything enclosed by those tags).


The web works like a interwoven collection of pages, and linking them together will be these a tags (a for anchor). These tags have an attribute href (hyperlink reference), which points to the location you want to redirect your readers to. And this is how you use it:

<a href='http://www.google.com' target='_blank'>
    Link to google
    <img src='path/to/img'/>

Yep, you can put images in your a tags too. Actually, you can put in anything basic tags under the sun and it will work.

Adding more structure

Most pages will have a certain page structure to it, header,content, footer, at least. The basic containers for most elements are the div and span tags.

But in html5, there are many more tags that can better segmentalized your page into the appropriate sections.

Basic containers

The most basic tags are the div and span. There are a few difference between them. div is for block elements and span is for inline elements.

Block elements refers to a whole section of the page which are displayed as blocks of content. These usually refer to section of the page, such as header, navigation bar or footer.

Inline elements as their names suggest, refers to a small portion of content, within a block to which specialized styling (usually through CSS) is applied to.

HTML5 section tags

In HTML5, there are much more section tags that helps add structure to the documents.

header is a section tag for containing the header content. It can include your logo, your page header, and whatever you plan on putting in your header section.

footer serves the same function as the header tag, a container for footer content (including copyright and contact information).

article contains the main content for the document. But if they are sections in the article, you can use the section tag to separate your content.

nav tags are for navigation. It will consist the links to the different sections of your website (home, about, etc).

aside tags are for sidebars which contain additional bits of information (description for blogs for example).

There are more of course, you can view all that here.

Special Content

In HTML5, there are many new semantics tags added to give structure to your documents.

Pre VS Code

We talk about the code tag just now. But for whole sections of codes, we use the pre tag to contain whole sections of code, preserving the newlines and whitespaces, keeping all the indentation intact.

function add(x, y){
    return x+y;


The figure tag is used to contain illustrations and pictures. The figcaption is used to add description to the figure. This all is written in the following manner:

    <img src='http://lorempixel.com/400/200/' />
        Some random picture from lorempixel


The audio tag is used to embed an audio resource into the page.

<audio src='test.mp3' type='audio/mpeg' />


video tag is similar to audio tag, but with videos instead of audio files.

Canvas & SVG

The canvas and svg tags are used for drawing things on the page. The canvas tag is controlled using javascript. The svg tag draws using xml. Learn more about canvas and svg.

What’s next

  • Forms (text input, form submission)
  • Tables (systematic display of info)
  • Separators (line breaks)

pouchdb – mysterious “document update conflict” error

pouchdb is a fairly useful offline database library if you are developing web app that needs data storage. After looking through the api, I started work, playing around with it, thinking that it should be fairly easy to.

I tried to implement the mother of all data storage test – incrementing a stored value. This is first version of the code I have.

var db = new PouchDB('test');


        // if _id exists, pouchdb overwrites
        db.put({_id:'1', value:d.value+1});

Well it seems like everything should work fine, especially when this is one of the most basic database function of all. But pouchdb is not simple technology.

I spent at least ten minutes struggling with this error here: document update error

What can be the problem? Everything seems to work fine. Google was my first go-to. I found this article by pouchdb’s author. I had a brief read, and it looks promising (promises, get it?). I plough through all 20 plus paragraph of the article.

JavaScript promises (not my solution)

After having a better understanding of how JavaScript promises work and how to use them properly, I tried to fix my code (the trial and error method).

My catch function is in the wrong place. Initially, I placed it there to catch the error where the entry is not found. But db.put may return an error too. The function should be placed behind in order to catch both errors, from both db.get and db.put.

After the changes, the second version of the code will look like this.

var db = new PouchDB('test');


        // if _id exists, pouchdb overwrites
        return db.put({_id:'1', value:d.value+1});

Returning the db.put promise is crucial. It ensures that the catch callback is applied to it too. So if anything goes wrong with updating the file, we will know too.

I prayed hard and tried again. Still doesn’t work.

Keep updating it until it works (not my solution)

I scouted through Google again. This time, I saw the upsert plugin. As it turns out pouchdb is pretty raw and basic. Many of the high level functions have to be implemented by the developers themselves.

This function I have is something like a upsert function. You update when there is a record, you return error when it’s missing. And the plugin’s way of doing it is to keep calling the db.put function over and over, until the query finally gets completed.

Here is what I have after implementing the upsert function.

var db = new PouchDB('test');

function update(){
        return db.put({_id:'1', value:d.value+1});

Hopefully that will solve the problem. But no, I ran the script and I keep getting the update error, over and over again. Oh noes, let double check that code again. Why doesn’t it work yet, argh…

That small little detail right there

I really need some in depth search for this. When to pouchdb’s github repository and looked through the issues opened.

And to my pleasant surprise, I found this piece of gem. It looks exactly like the problem I am having. But what’s with all those _rev he is talking about? I delved into the JavaScript console and played around with the library.

Indeed, with each record, there is both a _id and _rev. After some intense googling and source code reading, this is what I have figured out.

Pouchdb uses the variable to keep track of its documents, so when updating the database, it must be included to let pouchdb know that it is the same record.

As such, it will be easier to alter the object returned from db.get and use it in db.put since all the required elements are there, intact, untouched. The code will look like this after the changes are made.

var db = new PouchDB('test');

function update(){
        d.value += 1;
        return db.put(d);

Why it works?

In order for pouchdb to sync with remote server, a git like system is implemented to help the database keep track of changes. So for each record there will be a _rev to keep track of the status of the document.

How does that help with syncing? When the document used to update the database has a different _rev value, it can mean two things — the database is seriously out of sync, or a document is being overwritten, both contributing to loss of data.

To prevent any thing from going wrong, pouchdb checks every record to make sure they are of the same version, hence the update error. To trick pouchdb into thinking that everything is alright, the object must contain the _rev variable, and the shortcut is just to make the changes to the record itself, which was in my final implementation of the function.

Telegram Tumblr Bot

Tumblr for telegram

I have recently decided to start my development blogging. Not just the typical tutorial posts and promotional posts that I have been writing, but more of the everyday kind of development postings.

I have picked tumblr, as it is fairly mature (stable services), and the casual nature of tumblr makes it easier for me to write freely. It takes off the stress of having to produce good, easy-to-read pieces. It will just be a place where I post whatever comes along.

However, I do not want to have to download the tumblr app just to do my random journal entries. Most tumblr app is built more for viewing tumblr stream, which I have little interest as of now. I have tried other apps, but most of them follow the same nature of using tumblr as a information stream.

Convenient postings

I have tried email posting, but because the emails are sent out as text, it screws up the formating of the posts (fixed newlines). Hence I came up with the idea of sending the posts to telegram and then let telegram do all the posting, some like a “email posting 2.0”.

Tumblr for telegram

I have invested quite abit of time on the design of the app workflow. Learning from the previous telegram app, which was quite difficult to use (according to feedback). I have added useful guides along the way to help people more easily get started.

Try it out at @tumblr_pbot