Pages

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday, June 16, 2015

Core Javascript


Classes In Javascript


1. Using a function

This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for an object created using function(), you use the this keyword, as seen in the following example.

   Process = function()
    {
        this.a = 12;
        this.Step = function(){
            this.a=13;
            alert(this.a);
        }
    }
    var obj = new Process();
    alert(obj.a)
    obj.Step();

 OR
    clsPerson = function()
    {
        this.per = "This is";
        clsPerson.prototype.employee = function(){
            this.per += " another ";
            alert(this.per + "employee method");
        }

        this.accountant = function(){
            alert(this.per + "accountant method");
        }

        clsPerson.prototype.hr = function(){
             this.per += " so ";
             alert(this.per + "hr method");
        }
    }
    var obj = new clsPerson();
    obj.employee();
    obj.accountant();
    obj.hr(); 

2. Using object

Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do:

var o = {};
instead of the "normal" way:
var o = new Object();
For arrays you can do:
var a = [];
instead of:
var a = new Array();
So you can skip the class-like stuff and create an instance (object) immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:
    var step = {
        a: 12,
        process: function(){
            a = 13;
            alert(a);
        }
    }
    alert(step.a);
    step.process();


3. Singleton using a function

The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object.

    var step = new function(){
        this.a = 2;
        this.prcoess = function(){
            this.a=3;
            alert(this.a);
        }
    }
    alert(step.a);
    step.prcoess();

Understanding JavaScript Closures

In JavaScript, a closure is a function to which the variables of the surrounding context are bound by reference.
    
 A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.

You create a closure by adding a function inside another function.
A Basic Example of Closures in JavaScript:

   function showName (firstName, lastName) 
       {

          ​var nameIntro = "Your name is ";// this inner function has access to the outer function's variables, including the    parameter​
         ​function makeFullName () {
      
              ​return nameIntro + firstName + " " + lastName;
  
         }
        ​return makeFullName ();

        }

   showName ("Michael", "Jackson"); // Your name is Michael Jackson

Closures are used extensively in Node.js; they are workhorses in Node.js’ asynchronous, non-blocking architecture. Closures are also frequently used in jQuery and just about every piece of JavaScript code you read.
A Classic jQuery Example of Closures:


  $(function() {
    ​var selections = [];
        $(".niners").click(function() { // this closure has access to the selections variable​
           selections.push (this.prop("name")); // update the selections variable in the outer function's scope​
        });
    });

Another Example:-
function getMeAClosure() {
    var canYouSeeMe = "here I am";
    return (function theClosure() {
        return {canYouSeeIt: canYouSeeMe ? "yes!": "no"};
    });
}
var closure = getMeAClosure();
closure().canYouSeeIt; //"yes!"

Monday, March 19, 2012

LightBox problem with Internet Explorer


Its usually find that Lightbox create some problems with IE. Recently i was working in lightbox and faced the same problem. Lightbox gallery work fine in every browser except IE. After some Googling i found the following solution to the problem.

First:-

Put all the javascript Ref at the bottom of the web page but before closing tag i.e </body>
instead of head tag.

Code snippet:

<body>
<div>HTML data<div>
<div>HTML data<div>
<div>HTML data<div>
   <script src="/lib/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="/lib/jquery.jcarousel.js" type="text/javascript"></script>  
</body>

Second:-

Call jquery noconflict method to remove confliction between jquery libraries. Have a look at below piece of code.

Code snippet:

<body>
<div>HTML data<div>
<div>HTML data<div>
<div>HTML data<div>
   <script src="/lib/jquery-1.6.2.min.js" type="text/javascript"></script>
    jQuery.noConflict()   
    <script src="/lib/jquery.jcarousel.js" type="text/javascript"></script>  
</body>

Above ways help me to solve the lightbox problem in IE.
Hope it will be helpful for you all.

Thanks,
Amit

Sunday, February 12, 2012

AJAX in Javascript


What is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object (IE5 and IE6 use an ActiveXObject).

The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object

All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:
variable=new XMLHttpRequest();

Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:
variable=new ActiveXObject("Microsoft.XMLHTTP");

To handle all modern browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject:
Example
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

Method     Description
open(method,url,async)     Specifies the type of request, the URL, and if the request should be handled asynchronously or not.

method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string)     Sends the request off to the server.

string: Only used for POST requests

GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

    A cached file is not an option (update a file or database on the server)
    Sending a large amount of data to the server (POST has no size limitations)
    Sending user input (which can contain unknown characters), POST is more robust and secure than GET

GET Requests

A simple GET request:
Example
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();

Try it yourself »

In the example above, you may get a cached result.

To avoid this, add a unique ID to the URL:
Example
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();


Server Response

To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.
Property     Description
responseText     get the response data as a string
responseXML     get the response data as XML data

The responseText Property

If the response from the server is not XML, use the responseText property.

The responseText property returns the response as a string, and you can use it accordingly:
Example
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Try it yourself »

The responseXML Property

If the response from the server is XML, and you want to parse it as an XML object, use the responseXML property:
Example

xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
  {
  txt=txt + x[i].childNodes[0].nodeValue + "<br />";
  }
document.getElementById("myDiv").innerHTML=txt;

Tuesday, January 24, 2012

Calculator for adding dynamic numbers in javascript

Problem:- Genrate dynamic textboxes for adding dynamic numbers. If user entered three in textbox than genrate three textboxes and add values entered in that textboxes by user. Below is the code in javascript for solving problem.
This calculator can add two-digit numbers and display the result. First enter how many numbers you want to enter and press Change button. Then enter your numbers in the table and press Recalculate. Any blank or non-numeric input would be skipped while adding the numbers



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Javascript Calculator</title>
</head>
<body>
    This calculator can add two-digit numbers and display the result. First enter how
    many numbers you want to enter and press Change button. Then enter your numbers
    in the table and press Recalculate. Any blank or non-numeric input would be skipped
    while adding the numbers.<br />
    <br />
    <br />
    Number of Rows:
    <input type="text" id="NumberToAdd" value="" style="width: 30px" maxlength="2">&nbsp;&nbsp;<input
        type="button" value='Change' onclick="javascript:NumberToAdd(this) " />
    <br />
    <br />
    <table cellspacing="0" cellpadding="4" id="tblID">
    </table>
    <input type="button" value='Recalculate Sum' onclick="javascript:AddTotal()" />
</body>
</html>
<script language="javascript" type="text/javascript">

    //function Get the input from user for total number to be add
    function NumberToAdd() {
        //Clear existing HTML
        DeleteAllRows();
        //Get total numbers of rows dynimcally add
        var totalNumber = document.getElementById("NumberToAdd").value;
        if (totalNumber != null) {
            //Genrate rows as per input given by user i.e 'totalNumber'
            for (var i = 1; i <= totalNumber; i++) {
                addRow("tblID", i);
            }
        }
        return false;
    }

    //Remove all existing rows
    function DeleteAllRows() {
        var table = document.getElementById('tblID');
        var rows = table.rows;
        while (rows.length)
            table.deleteRow(rows.length - 1);
    }

    //function adding row at runtime
    function addRow(tableID, i) {
        //Get table object
        var table = document.getElementById(tableID);
        //Find total numbers of rows
        var rowCount = table.rows.length;
        //Add row count to table
        var row = table.insertRow(rowCount);

        //Add Label to first cell of row
        var cell1 = row.insertCell(0);
        var element1 = document.createElement("label");
        element1.type = "label";
        element1.innerHTML = "Number" + i;
        cell1.appendChild(element1);

        //Add Input control to second cell of row
        var cell2 = row.insertCell(1);
        var element2 = document.createElement("input");
        element2.id = "number" + i;
        element2.type = "text";
        element2.maxlength = "2";
        cell2.appendChild(element2);
    }

    //function Adding the number as per rows data added at runtime
    function AddTotal() {
        var total = 0;
        var totalNumber = document.getElementById("NumberToAdd").value;
        for (var i = 1; i <= totalNumber; i++) {
            if (document.getElementById("number" + i).value != "" && (parseInt(document.getElementById("number" + i).value)).toString() != "NaN")
                total = parseInt(total) + parseInt(document.getElementById("number" + i).value);
        }

        //Check weather Result element exist
        if (document.getElementById("result") == null) {
            //Adding row to show add total result
            var table = document.getElementById("tblID");
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            row.id = "result";

            //Add Label to first cell of row
            var cell1 = row.insertCell(0);
            var element1 = document.createElement("label");
            element1.type = "label";
            element1.innerHTML = "TOTAL";
            cell1.appendChild(element1);

            //Add Input control to second cell of row
            var cell2 = row.insertCell(1);
            var element2 = document.createElement("label");
            element2.id = "resultCell";
            element2.type = "label";
            element2.innerHTML = total;
            cell2.appendChild(element2);
        }
        //if result element exist then override the result
        else
            document.getElementById("resultCell").innerHTML = total;
    }


</script>