Thursday, September 15, 2016

Why call and apply two methods available in JavaScript

I hope everyone know about what is call and apply. Just for reminder,

The call() method calls a function with a given this value and arguments provided individually

 myFunction.call(thisArg[, arg1[, arg2[, ...]]])

The apply() method calls a function with a given this value and arguments provided as an array

 myFunction.apply(thisArg, [argsArray])

So both call and apply do similar job as to change the scope of function in which it gets executed (change this of function). So why exactly JavaScript has these 2 methods, one to pass array as an argument and another as the comma separated args. As per my experience in JavaScript I found few places where actually we can use apply but not call. May be you got some other examples also then please share. I would like to take one example here. Suppose we need to find out the min in a given array of integer (unsorted), what will be your approach? First approach we can think to search and find min or sort the array and find min. But if the question is, you have 5 numbers and find out the min of these 5 numbers, now can you think to use Math library (Math.min) in this case and find out min

 // we can pass individual numbers comma separated in Math.min and find out min easily
 Math.min(4,1,8,3,7) // 1

Now think about using array here.......??? can we pass array in this Math.min ? ..... Yes we can !

 var ar = [4,1,8,3,7];
 Math.min.apply(undefined, ar) // 1

Now suppose if only call is available in javascript we can not achieve this using call

In ES6 there is one more way to achieve this. Spread/rest parameter

 var ar = [4,1,8,3,7];
 Math.min(...ar) // 1
Know more about spread/rest parameter

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);

Friday, July 15, 2016

Create Message in Hindi by typing in Hinglish

If you want to write something in Hindi but want to type in hinglish then this is the correct place just write in English (Hinglish) and when you press space english will change to Hindi. Enjoy writing.
Create your messages in hindi and spread the love
Use Ctrl + C to copy the message OR right click and copy

You can share your message with your friends or family

Wednesday, June 29, 2016

Concentration Circle

Hello Friends in this busy schedule we do not have time for doing yoga and exercise, we should do some exercise daily to keep our body and mind both healthy. Below is one concentration circle it is the exercise for sharpen the mind.

If you just focus on black center of circle with full concentration then surrounded radiant color part will disappear. Try this 2 minutes mind exercise to sharpen your mind.

Sunday, June 26, 2016

Input Validation with Styling anywhere in your site

Hello Friend, When we have input fields in our websites then many custom styling we apply or required for form validation. For example if user entered something, if user changed the value of input, is input empty. Many more depend on user actions.

Here I created one small utility which you can add in your site code and all the inputs of your project can be validated using this, without adding any extra code. Below is the code which you need to add in JavaScript.

function inputValidator(inputSelector) {
  var current_val = $(inputSelector).val();
  function onChange() {
    $(this).removeClass("dirty").addClass("pristine");
    this.updated_val = $(this).val();
    if (this.updated_val != current_val) {
      $(this).removeClass("pristine").addClass("dirty");
    }
  }
  function onFocus(){
    $(this).removeClass("untouched").addClass("touched");
  }
  $(inputSelector).on("input change", onChange);
  $(inputSelector).on("focus", onFocus);
  return true;
}

$(document).ready(function() {
  $.each($("input"), function(key, value) {
    new inputValidator(value);
  });
});

When you add above code in your javascript, then all input will have one class "untouched" by default. Class of input will change on user action, and you can apply style on input based on classes.

  • By default class is untouched
  • When you touch the input, class will change to "touched"
  • When you enter something in the input, class will change to "touched dirty"
  • When you revert you changes in the input, class will be "touched pristine"

For example, if our inputs are as shown below:

Text:

Email:

Password:

Number:

Date:

CSS code that I have written for inputs:

.name{
  display: inline-block;
  width:80px;
}
input.untouched{
  background-color: #DDF4FC;
}
input.touched{
  background-color: #6AFAFA;
}
input.touched.pristine{
  background-color: #43FF44;
}
input.touched.dirty{
  background-color: #FF4422;
}

Now if user interact with inputs, colors changes as mentioned in css style

Here is the codepen link : http://codepen.io/JitendraPal/pen/MebLoX

Thursday, May 19, 2016

Spread operator or Rest parameter or Ellipsis in JavaScript (ES6)

Spread/Rest/Ellipsis operator in JavaScript is very useful in many context. First important use of this operator is to pass indefinite number of argument in function

Operator syntax: ...name

Three dot and then a variable name

 function sum(a,b,...n){
  return a+b+n[0]+n[1];
 }
 sum(1,2,3,4); // output: 10 

This is also called rest parameter. inside function it can be used directly as array.

As we already know that arguments is already available in function to get many parameters as shown below: but actually that is not array

function fun(){
 return arguments[0] + arguments[1];
}

fun(1,2); // 3


function fun2(...n){
 console.log(arguments);
 console.log(n);
}

fun2(1,2,3); // it will print arguments object and array n.

There are other advantages of spread operator. Suppose we have 2 arrays and need to merge both

var a = [1,2,3], b = [4,5,6];
a.push(...b);
console.log(a); // [1,2,3,4,5,6]

Sunday, April 24, 2016

AngularJS advanced trick and techniques

These days AngularJS is highly recommended framework for front-end developer. Angular is really awesome framework to work with. Below are few techniques those I feel really cool features and may be these are simple and easy for you but as a fresher in angular I think these features are really good.

1. How to add multiple classes in ng-class?

Everyone knows how to add class using ng-class, its very easy. We can use ng-class to have more than one class as well

 
// single class
// multiple class
some content

Similarly we can add many classes separated by comma (,)

2. Can we have multiple conditions in ng-hide and ng-show?

Yes, we can have multiple conditions in ng-hide and ng-show.

// ng-show with multiple conditions
Some content

3. How to share methods or data between controllers?

Yes we can share data and methods between controllers using Factory or Service. Angular has service as constructor method which instantiate once on startup and we can use this service/factory in any controller within the module by injecting on controller method.

Restrict input to allow only required value (jQuery plugin for input type validation)

HTML5 provides many validation on input, but still few we need to implement by our self. For example, if we need one input for price then we should allow users to enter only float values. I created one small plugin using jQuery, it is very easy to use.

To create one input with only price value then just include attribute "only-price"


To create one input with only number (contact) value then just include attribute "only-number"


Here is the codepen: http://codepen.io/JitendraPal/pen/JXBqXj

Saturday, April 2, 2016

Git Hub configuration All About

Hello Friend, Most of the time when I am working with git hub. I forgot few commands. To help myself I am writing this post, and its my pleasure if this post helps other as well.

Below are commands those are self explanatory:

  1. To clone your branch in local

    $ git clone [your git repository url]
  2. Clone specific branch in local

    $ git clone [your git repository url] -b [branch name]
  3. OR
    $ git clone -b [branch name] [your git repository url]
  4. After cloning your branch go to that branch to check branch status or perform any git operations, below command will show you current branch

    $ git branch
  5. Checkout specific branch from git

    $ git checkout [branch1]
  6. Merge branch2 into branch1

    $ git merge [branch2]
  7. Stash your changes before pull

    $ git stash
  8. Pull latest changes from current branch

    $ git pull
  9. Get stashed changes back into local

    $ git stash apply
  10. Add all your changes

    $ git add -A
  11. Add specific files

    $ git add [/file path] [/another file path] [..etc]
  12. Commit your changes with message

    $ git commit -m "[your message]"
  13. Push your committed changes in the branch

    $ git push origin [branch name]
  14. Pull latest changes

    $ git pull --rebase
  15. Create new branch and checkout in this branch

    $ git checkout -b [your new branch name]
  16. Push the branch on git hub

    $ git push origin [your new branch name]

Friday, February 12, 2016

How to use factory or service in AngularJS

As a beginner in AngularJS it is very important to understand Service/Factory. AngularJS provides many services itself and we can use those services whenever we required, just by injecting in controller/module.

when we need to share some functions or some data we can create our own service/factory and have all the methods/data in that. To use these service's method or data we just need to inject that service and use.

For example if we want to share one data object in 2 different controller, say controller1 and controller2. We Create one service dataService

 var app = angular.module("app",[]);
 app.factory('dataService',['$http', function($http){
  var dataService = {};
  dataService.method1 = function(){
    console.log("method1 executing");
  };
  dataService.method2 = function(){
    console.log("method2 executing");
  };
  return dataService;
 }]);
 

Now we can use this service in any controller by injecting

app.controller('controller1',['dataService','$scope' function(dataService,$scope){
 dataService.method1();  // it will print 'method1 executing'
 dataService.method2();  // it will print 'method2 executing'
}]);
app.controller('controller2',['dataService','$scope' function(dataService,$scope){
 dataService.method1();  // it will print 'method1 executing'
 dataService.method2();  // it will print 'method2 executing'
}]);

In same way we can create service also instead of factory, the only difference between factory and service is that, service is constructor function while in factory we need to return the object. For same objective we can create service as follows:

 app.service('dataService',['$http', function($http){
  this.method1 = function(){
    console.log("method1 executing");
  };
  this.method2 = function(){
    console.log("method2 executing");
  };
 }]);

Sunday, January 31, 2016

How to add AngularJS in rails application, error: rails:undefined method `register_engine' for nil:NilClass (NoMethodError)

Adding AngularJS in rails application is very easy. Just add angular-rails-templates in gem file as shown below:
  gem 'bower-rails'
  gem 'angular-rails-templates'

But some times it gives error and does not run as expected. This issue is might be because of sprocket version. We have to mention sprocket version in gem file

  gem 'sprockets', '2.12.3'

After adding sprocket in the gem file, update bundle

  $ bundle update
  $ rails g bower_rails:initialize json

Now open bower.json file and add angular in the library dependencies

{
  "lib": {
    "name": "bower-rails generated lib assets",
    "dependencies": {
      "angular": "latest",
      "angular-route": "latest"
    }
  },
  "vendor": {
    "name": "bower-rails generated vendor assets",
    "dependencies": {
    }
  }
}

One more important thing REMOVE turbolinks from gem file and from application.js file, and add angular in application.js file

//= require angular
//= require angular-route
//= require angular-rails-templates

For the reference below is my gem file

source 'https://rubygems.org'

gem 'sprockets', '2.12.3'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.4'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

gem 'angular-rails-templates'

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'

  gem 'bower-rails'

end


group :development do
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'

  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
end