Saturday, August 27, 2016

Align Element in Center

Align element in centre position of the screen using only CSS

Horizontal alignment is very easy on the screen. But some times alignment in vertical is very difficult

Horizontal alignment

To align an element horizontally best approach is using margin

 margin: 0 auto;

Vertical alignment

To align an element vertically we can use this approach

  transform: translateY(-50%);
  position: relative;
  top: 50vh; 

There is one another approach to center it using CSS3 flex property

 // on the parent element we just need to apply flex properties
  height: some height;
  display: flex;
  justify-content: center;
  align-items: center;
You can check on codepen: Codepen

If you have any other approach please share.

Wednesday, August 24, 2016

Block level scoping in JavaScript

Block level scoping in JavaScript

If you are familiar with JavaScript. If you are working as FE developer then must be aware that JavaScript has functional level scoping not block level scoping as in C family languages.

Now, from ES6 JavaScript introduces let keyword. "var" keyword is still there which will function in same manner as it is currently. Using let keyword you can declare one variable inside one block and its scope will be in that block only as block level scoping in C family languages.

For example
// using var only
function myFun(){
 var a=1;
 if(a>0){
  var b=2;
 }
 console.log(b);
}

myFun(); // 2

// using let keyword
function myFun2(){
 var a=1;
 if(a>0){
  let b=2;
 }
 console.log(b);
}

myFun2(); // Uncaught ReferenceError: b is not defined

In above example second function myFun2 gives error as let has block level scoping only and it is declared inside if block so it is not available out side if block.


Saturday, August 6, 2016

Clone/Copy JavaScript Object

Creating an Object copy from an object was not easy earlier in JavaScript (before ECMAScript 2015). Now as ECMA 2015 is available we can use Object.assign to create copy of an object.

Create clone/copy of an object before ECMAScript 2015

 var obj1 = {a:1,b:2}, obj2;
 // one simple way is to stringify and then use
 obj2 = JSON.parse(JSON.stringify(obj1));
 console.log(obj2); // {a:1,b:2} 

Clone/Copy after ECMAScript 2015

Now ECMAScript 2015 provided assign method in Object so that we can create clone/copy of an object. For method is available chrome 45 onwards.

 var obj1 = {a:1,b:2}, obj2;
 obj2 = Object.assign({}, obj1);
 console.log(obj2); // {a:1,b:2}
 
 // another way to use same method (assign)
 var obj3={x:1, y:2}, obj4 = {};
 Object.assign(obj4,obj3);
 console.log(obj4);