Height responsiveness using calc() CSS

I like to share a small use case of calc() CSS which helped me to achieve height responsiveness.

My use case is as follows

  1. A parent element with some static height.
  2. Three child elements (for reference let’s name them as c1, c2 and c3)which should fill the parent.
  3. Out of the three child elements, two of them(c1 & c3) will have static height and the c2 has to occupy the remaining space.
  4. And the c2 has to adjust its height on window resize without disturbing it’s siblings.

To achieve this, I need to calculate the height required by the c2, initially I tried the below solution to find the height.

  1. Calculate the sum of height of two child elements(c1 & c3).
  2. Calculate the height of parent element.
  3. Now height of the last child element calculated from the equation – height of parent – sum of height of c1 & c3 elements.
  4. Set the resultant height to the c2 child element.
  5. To auto adjust the height on window resize, register a resize callback and repeat the step 1 to 4.

Well, this method will work well but it could be done better.

How can it be done better?

Here comes the calc CSS. There are many usages available for calc CSS one of the them is unit mixing which is going to help me with this.

So my requirement will be achieved with the following steps.

  1. Calculate the sum of height of two child elements(c1 & c3).
  2. Now set the height to the c2 child element as height: calc(100% - height from step1).

That’s it. Now all the child elements will fit within its container whereas the c2 child will use the remaining space leave by c1 and c3.

Also it’s worth to note that this will allow the c2 element to adjust its height on window resize without using a resize event handler.


  1. MDN: calc CSS
  2. CSS Tricks: A couple of use cases for calc

Angular 2 – How to get template reference variable or directive instance inside component

In this post let us see how to get Angular 2 directive/child component instance inside the parent component class.

ViewChild in action
The ViewChild decorator can be used to achieve this requirement.
The ViewChild accepts either the directive type or the template reference variable as argument and set the directive instance to the target property after the view get initiated.

  selector: 'child-cmp',
  template: '


class ChildCmp {
  doSomething() {}
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
  directives: [ChildCmp]
class SomeCmp {
  @ViewChild(ChildCmp) child:ChildCmp;
  ngAfterViewInit() {
    // child is set

The ViewChild will set the target property once the component view get rendered hence accessing the property before the view get initiated will return inappropriate result.

You can use the ngViewAfterInit lifecycle hook to identify the view initialization.

Argument as Directive type vs template variable
Using argument as template variable ViewChild is best from my point of view as it will provide access to specific directive instance when having more than one directive in the template.

  selector: 'some-cmp',
  template: '<child-cmp #child></child-cmp>',
  directives: [ChildCmp]
class SomeCmp {
  @ViewChild('child') child:ChildCmp;
  ngAfterViewInit() {
    // child is set

Happy Scripting.. ­čÖé

DOM creation and manipulation tips and tricks

In this post, I would like to share a simple DOM creation and manipulation technique which will provide some performance boost.

The goal of this post is to improve browser DOM manipulation performance by reducing unwanted reflow and repaint process. If you are unaware of them you should go through the below topic before getting started with this post.

Reflow and repaint

Use Document fragment
This is an already known technique. Using document fragment allow the separation of DOM creation from live document so that it will avoid unnecessary browser reflow and repaint.

var fragment= document.createDocumentFragment();

Clone nodes
Cloning already created element using cloneNode. This will be helpful when creating large number of same element. Mostly likely it can be used while creating table tr elements from JSON.

var fragment= document.createDocumentFragment();
var div = document.createElement("div");

Batch DOM update
Always batch the DOM update. Batch the DOM changes will reduce browser reflow and repaint.

Using requestAnimationFrame for DOM changes
This technique will provide a considerable performance when changing the live document. requestAnimationFrame will be used to update the DOM changes when the next reflow/repaint happens.
Normally it is introduced to do smooth animation experience in browser but here we can use this to do a single DOM update.

  document.body.appendChild( document.createElement("div") );

Use insertAdjacentHTML instead of innerHTML
This will be used when we need to append dynamic content to the same element.
We can use the innerHTML as follows.

var div = document.createElement("div");
div.innerHTML ="Hi" //<div>Hi</div>

div.innerHTML += " Dude"; //<div>Hi Dude</div>

But the above one have significant performance impact as it needs to re-parse all the child element already present.
To overcome this we can use insertAdjacentHTML which will append the inner HTML without touching the other elements. It only parses the new HTML need to be appended.

var div = document.createElement(&quot;div&quot;);
div.innerHTML = "Hi";  //<div>Hi</div>

div.insertAdjacentHTML("afterend", " Dude"); //<div>Hi Dude</div>

Following the above methods will provide a better performance in most of the modern browsers.

Happy scripting….

Replace () as call back function

We know that the replace() method will return a new string based on the pattern and its corresponding replacement argument.

Here the pattern can be either general string or regular expression that we normally use. And for replacement argument in most cases we use string as replacement. But there is an extensible facility to use this replacement as call back function.

Here we go with a small example code snippets.

Code Snippets:

var numbers = '34 55 27 45 72',
type1 = numbers.replace(/\d+/g, '*'),
type2 = numbers.replace(/\d+/g, function (item) {
return +item < 50 ? '*' : item;
console.log("simple replace() : ", type1);
console.log("replace() with call back function : ", type2);

Fiddle Demo


The call back function will be invoked for the each matched set of an item, when the first parameter regular expression is declared as global.

Deleter – Node based directory removing tool

My first node package deleter, has been released. Its a CLI, which is used to remove directories. I come up with idea to create this when i faced difficulties in deleting node_modules from my node based applications.


npm install deleter -g

Since it is a CLI, global installation is preferred.


deleter <directory-name>


deleter node_modules


For now, its target for windows operating system and other OS will be considered in upcoming updates.



Why new keyword should be used while instantiating JavaScript class

The new keyword is used to instantiate prototypical class or other objects. But why we need new keyword to initialize it, when you to try to initialize it without new will not throw any error at all then why should I use new before my class to instantiate it.

The answer is simple new keyword will set the ‘this’ to the new object created using function instead of global scope”.

If you didn’t provided new keyword then the context will be set to window(global scope).

You can see the difference in the below code example.

var fn = function (){
       this.a = 2;
       return this;

Instantiating fn without new keyword.

 var f = fn();  //`this` refers window here.

Instantiating fn with new keyword.

 var f = new fn();  //`this` refer object created by `fn` here.

Even though using new keyword is the best practice to instantiate class, most of the time, the users will skip them as it doesn’t provide any error at all.

We can use the below simple workaround to enforce the instantiating process using new keyword. Then the above fn will become as below.

 var fn = function (){
       if(!(this instanceof fn)) //workaround to resolve this problem.
          return new fn();
       this.a = 2;
       return this;

Now instantiating without new will also set this to the current object.

 var f = fn();  //this refer to fn here.

Instantiating class/function without new keyword in ES6 will throw TypeError.

Happy Scripting… ­čÖé

Some alternative use of bit wise operators

In this blog, I am just going to share some of the alternative use of the bitwise operators.

1. Replace Math.floor with double ~~.
Even though JavaScript Math library is well optimized, we can use the bitwise operators to reduce some keystrokes.

~~3.4 //result : 3

2. Convert to Boolean using !!
Double NOT operator is used to convert any type into Boolean.

var d = &amp;quot;Hi&amp;quot;;
!!d //result : true
var f = null;
!!f //result : false

3. Swap values without temp variable using XOR.
It is the one of the common method used to swap two variables without using temp variable.

var a = 5, b= 6;
a ^= b; b ^= a; a ^= b; //result a = 6, b = 5;

4. Using left and right shift with 1 bit to perform multiply and division.
Left shifting a number 1 bit is equivalent to the result obtained by multiplying it by 2 and right shifting 1 bit is equivalent to dividing it by 2.

var d = 4, f = 6;
d >> 1 //result : 4 * 2 = 8
f << 1 //result : 6 / 2 = 3

5. Checking odd/even using AND with 1
Performing AND operation with 1 will return value greater than 0 if its odd. We can use it simply to find whether a number is odd or even.

var a = 5, b= 6;
a & 1//result 1 - odd
b & 1//result 0 - even

Happy Scripting…

Deserialize JSON to instance of JavaScript class

Prototypical class is used to create classes in JavaScript like other programming languages.
The object return from these classes will have corresponding class information. When you to try to serialize and de-serialize this object, the class information associated with the corresponding object will be removed.

In this post, we are going to see how to retrieve this class information and make the object as the instanceof corresponding class.

The process involves two steps. They are

1. Parse using JSON.parse method.
2. Assign the constructor of the actual class to the __proto__ property of the parse JSON.

Let us see this in details.

If we have a JavaScript class like below.

 var myClass = function(){
this.a = 1;
return this.a;

var d = new myClass(); //result: &amp;quot;{a:1}&amp;quot;;

d instanceof myClass //result: true;

In the above all works fine. The problem will arise if we try to check instanceof on the object from deserialization like shown below.

var str = JSON.stringify(d);

var d = JSON.parse(str); //result: &amp;quot;{a:1}
d instanceof myClass //result: false;

So now d lost its class information and hence it failed. Now we can use the below utility function to retrieve the class information.

var toCalss = function(obj, proto) {
obj.__proto__ = proto;
return obj;

var res = toClass(d, myClass.prototype);

res instanceof myCalss //result: true;

Now the object will have class information which makes the instanceof to work as expected.
Happy scripting..


Using Jquery Deferred

I am going to give a simple example which would explains the usage of Jquery deferred concept. The Jquery deferred plays a vital role in handling asynchronous actions. The $.Deferred is used internally by many Jquery API such as ajax and animations.

The $.Deferred usage flow will be as follows.

  1. Instantiate deferred object using $.Deferrred() when some action starts.
  2. When the action completed, resolve the deferred object using resolveWith/rejectWith and your parameter.
  3. Return the promise object from the function for chaining ability

Now I am going to explain using $.Deferred object with the simple animation operation.

For that we have a HTML element as follows.

<input type="button" value="Animate" />
<div id="target" style="border: solid 1px black; width: 500px; height: 70px;"></div>

And the function which will perform the animation is as follows. The below function will animate the width of the div element from 500px to 10px. I had not written the animate function in a generic way as I am going to concentrate on using deferred promise.

    function animate() {

            //Initialize Deferred object.
            var deffered = $.Deferred();   Step 1

            width = +$("#target").outerWidth();

            var inter = setInterval(function () {
                $("#target").width(width-- + "px");

                //Stops animation when width reaches 10.
                if (width == 10) {


                    //RESOLVE THE DEFERRED WITH arguments.
          Step 2 deffered.resolveWith($("#Grid"), [{ width: width }]);

            }, 10);
            //Returns promise object to chain operation.
         Step 3   return deffered.promise();

Now the animation function can be invoked as follows. And when the animation completed, the promise object will get resolved and call the corresponding callback registered using done. If fails, the callback registered with fail will be invoked.

       //Input element click handler.
        function change() {            

            animate().done(function (e) {
                console.log(e.width); //Returns 10


And I said in the Step 3 to return the promise object. But we should be careful in using this since it sometimes led to anti-pattern.

Monkey patching

Monkey patching is a technique that uses the flexibility of the JavaScript to modify any function/method behavior.

Performing monkey patching is simple and it can be done by the following steps.

  1. Store the original function in a variable
  2. Now modify the function behavior
  3. Call the original function using apply.

This can be useful when you want to change the argument values of the function. For example, consider we have the following class.


        var math = function () {
            this.a = 1;
            this.b = 2;

        math.prototype = {
            sum: function (a, b) {
                return a + b;

Now we can modify the method sum using the monkey patching technique as follows.

        var original = math.prototype.sum;   Step 1

        math.prototype.sum = function (a, b) {
            a = a * 2, b = b * 2;    Step 2

            return original.apply(this, [a, b]);    Step 3

On executing the above method, the result will as follows.

       var obj = new math();

        obj.sum(1, 2); //return 6;
        //Expected: 3, Actual : 6 due to monkey patch

Happy Scripting… ­čÖé