Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Creating a simple grunt task

Posted in Javascript

Grunt is a JavaScript task runner used to automate the common tasks such as JS/CSS file minimization, concatenation of multiple JS/CSS files, Sass compilation, JS linting, code formatting etc.

To get started with grunt you need to install node JS latest version from node JS website.

https://nodejs.org/

Create Node project

From node.js command prompt, go to the project directory.
grunt-1

Type: “npm init”, then: “enter”
grunt-2
follow steps, enter only a name for the site, no need to change other default values. “npm init” command creates a package.json file. Refer the screenshot below.
grunt-3

Install grunt
Use the npm command below to install grunt specific to your project.
grunt-4
–save-dev command adds the dev dependency in the package.json file.
package.json file will look like this.
grunt-5

Create Gruntfile.js in the project root directory. We will use this file to create and configure grunt tasks. Add the below code in the Gruntfile.js.
grunt-12

It’s time to create a grunt task. Create a simple grunt task named logTask using grunt.registerTask function.

  grunt.registerTask('logTask', function() {
    console.log('Inside Log Task');
  });

Your gruntfile will look like this.
grunt-6

Now call the logTask using the command below. “Inside Log Task” text will get printed in the console.

     grunt  logTask

grunt-7

You can create multiple grunt task in the same Gruntfile.
grunt-8

To call the formatTask use the command below.

    grunt formatTask

grunt-9

You can run the above tasks simultaneously by calling both task into the new task.
grunt-10

grunt-11

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Built in Angular JS Directives

Posted in Angular JS, Javascript

HTML 5 provides flexibility to create custom tags and attributes. Angular use the same HTML 5 concept to provide additional functionality using these custom tags and attributes. Angular JS has built in directives listed as below.

  • ng-app: Declares the root element of an Angular JS application, under which directives can be used to declare bindings and define behavior.
  • ng-bind: Sets the text of a DOM element to the value of an expression. For example, <span ng-bind=”name”></span> will display the value of ‘name’ inside the span element. Any changes to the variable ‘name’ in the application’s scope are reflected instantly in the DOM.
  • ng-model: Establishes a two-way data binding between the view and the scope. Mostly used with form controls such as Textbox, select dropdown, checkbox, radio button etc.
  • ng-class: Allows class attributes to be dynamically loaded.

     <div ng-class="{'classname': expression}"> ... >/div> 
  • ng-controller: Specifies a JavaScript controller that evaluates HTML expressions.
  • ng-show & ng-hide: Conditionally show or hide an element, depending on the value of a boolean expression. Show and hide is achieved by setting the CSS display style.
  • ng-switch: Conditionally instantiate one template from a set of choices, depending on the value of a selection expression.
  • ng-view: The base directive responsible for handling routes that resolve JSON before rendering templates driven by specified controllers.
  • ng-if: Basic if statement directive that allow to show the following element if the conditions are true. When the condition is false, the element is removed from the DOM. When true, a clone of the compiled element is re-inserted.
  • ng-disabled: Add HTML 5 “disabled” attribute based on the condition to disable any HTML element.
  • ng-options: The ng-options directive fills a <select> element with <options>.

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Get URL parameters using JavaScript

Posted in Javascript, javascript interview questions

Sometimes you might need to get URL parameters also called as query string parameters using JavaScript. URL parameters can be one or multiple.

Example:

http://localhost/mypage?id=10

Multiple URL parameters:

http://localhost/mypage?id=10&name=Simy

Use script below to get URL parameters:


function getURLParameter(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

Above function returns specified URL parameter based on the argument supplied to that function.

getURLParameter(“id”) –> Returns 10

getURLParameter(“name”) –> Returns Simy

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Search object in an array

Posted in Javascript, JQuery

You can find any element in an array based on index of that element. But what if you want to find an object in an array of objects based on any of the property. You can use filter function of JQuery.

JQuery filter (selection) function returns an element or array of elements that matches specified criteria. If provided selection parameter matches with any of the element in an array it returns that particular element or array of elements.

Example:

  $(selector).filter (selection, function(index){
       // Process elements here
  })
    Selector is a set of DOM elements or array of objects.
    Selection is a filter parameter which is used to match with the elements in array.
    function(index) is a callback function which used to process the elements in filtered array.

Example:

Consider an example of employee’s data. Find list of employee’s based on their age.

    var employees=[
        {name:"George", age:32, retiredate:"March 12, 2014"},
        {name:"Edward", age:17, retiredate:"June 2, 2023"},
        {name:"Christine", age:58, retiredate:"December 20, 2036"},
        {name:"Sarah", age:62, retiredate:"April 30, 2020"}
   ];

   var age=32;
   var employeesFound = employees.filter(function(obj) {
    return obj.age== age;
   });

In above case, employeesFound array contains an employee object with an age of 32. You can find employees with age greater than 32.

    var employeesFound = employees.filter(function( obj) {
     return obj.age> age;
    });

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

HTML5 sessionStorage Safari “QUOTA_EXCEEDED_ERR”

Posted in Html, Javascript

If you have opened a web page in private mode in ios-safari browser and if you are using sessionStorage/localStorage in your code sometimes you will get “QUOTA_EXCEEDED_ERR:”.

Error is highlighted below:

“QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota.”

This can be overcome by simply putting sessionStorage code in try catch block.

              if (typeof sessionStorage === 'object') {
		    try {
		        sessionStorage.setItem('sessionStorage', 1);
		        sessionStorage.removeItem('sessionStorage');
		        sessionStorage.setItem("questions", JSON.stringify(data));
		    } catch (e) {
		        Storage.prototype._setItem = Storage.prototype.setItem;
		        Storage.prototype.setItem = function() {};
		    }
		} 

The same code is applicable for localStorage also.

              if (typeof localStorage === 'object') {
		    try {
		        localStorage.setItem('localStorage', 1);
		        localStorage.removeItem('localStorage');
		        localStorage.setItem("questions", JSON.stringify(data));
		    } catch (e) {
		        Storage.prototype._setItem = Storage.prototype.setItem;
		        Storage.prototype.setItem = function() {};
		    }
		}