Tuesday, 11 March 2014

Javascript : How to debug?

Debugger -
It allows you to find the mistakes in your written programme
There can be chance that you would make a mistake while writing your programme.
and that mistake is referred to as a bug.

The process of finding and fixing bugs is called debugging and is a normal
part of the development process.

Now we will discuss tools and techniques that can help you to debug code.

I am using chrome as Example :

To see where error is throwing
-enter F12 (which will open inspect element) -> go to console
-you'll see character written with red color (showing error)
-see the rightmost side of error characters -> some js file will be there
->click on js file it will show you the error location
                                         
To debug the code :
In previous example we understood how to find the place of error in js file
Now we will fix the error
-> put the "debugger;" (without quotes) just before error is throwing or just
   inside the function in which error exist

Example :

function checkthis(){
debugger;
// your code here
}

Note :
while debugging you can go to console and check the value of variables

Example:

funtion checkthis(data){
debugger;
var b = data.item; // you can check this b value in console after debugger stepover this line
}

Javascript validator tools :
The most convenient validator for JavaScript is Douglas Crockford's
JavaScript Lint.
http://www.jslint.com/

Monday, 24 February 2014

Basic of Browsers

Bowsers : It signifies the webpage.A platform where webpage loads
               there are many different types of browser available with some different
               and its unique capability
               It is important to understand the differences between different browsers
               in order to handle them in the way we expected. So it is important
               to know which browser your Web page is running in.

To get information about the browser your Web page is currently running in,
use the built-in navigator object.

Navigator Properties:
There are several Navigator related properties that you can use in your
Web page. The following is a list of the names and descriptions of each:

Property                                                       Description

appCodeName  - contains the code name of the browser, Netscape for Netscape
                               and Microsoft Internet Explorer for Internet Explorer.
appVersion   -    contains the version of the browser as well as other useful information such as
                                its language and compatibility.
language     - contains the two-letter abbreviation for the language that is used by
                        the browser. Netscape only.
mimTypes[]   - This property is an array that contains all MIME types supported by
                        the client. Netscape only.
platform[]   - contains the platform for which the browser was compiled. "Win32" for 32-bit Windows                               operating systems
plugins[]    - It is an array containing all the plug-ins that
                       have been installed on the client. Netscape only.
userAgent[]  - contains the code name and version of the browser.
                         This value is sent to the originating server to identify the client

Example :

<html>
<head>
<title>Browser Detection Example</title>
</head>
<body>
<script type="text/javascript">

var userAgent   = navigator.userAgent;
var opera       = (userAgent.indexOf('Opera') != -1);
var ie          = (userAgent.indexOf('MSIE') != -1);
var gecko       = (userAgent.indexOf('Gecko') != -1);
var netscape    = (userAgent.indexOf('Mozilla') != -1);
var version     = navigator.appVersion;

if (opera){
  document.write("its Opera ");

}else if (gecko){
  document.write("its Mozilla");

}else if (ie){
  document.write("its IE ");

}else if (netscape){
  document.write("its Netscape");

}else{
  document.write("Unknown browser");
}

document.write("<br /> Browser version info : " + version );

</script>
</body>
</html>
NOTE : you can type and test code in console (press F12) and check the navigator.useragent

Wednesday, 19 February 2014

Basics of Error Handling

Error Handling : When an error occurs user need to handle that error accordingly
                            and the method of handling these kind of error we called as Error Handling

There are three types of errors in programming:
(a) Syntax Errors
(b) Runtime Errors
(c) Logical Errors:

Syntax errors:
Syntax errors, as name denotes error caused by improper syntax
it is also called parsing errors, occur at compile time

Example:

<script type="text/javascript">

window.alert(; // syntax should be window.alert();  missing a closing parenthesis:

</script>

Runtime errors:
Runtime errors, as its name says the error happened on unning the script
it is also called exceptions, occur during execution after compilation.

Example :

<script type="text/javascript">

window.welcomeMe(); // there is no function name welcomeMe hence it throws error

</script>

Logical errors:
Logic errors is type of error which caused by wrong Logical implementation
it is most difficult type of errors to track down.
These errors are not caused by syntax or runtime error.

You can not catch those errors, because it depends on your
requirement what type of logic you want to put in your program.

The try...catch...finally Statement:
The latest versions of JavaScript comes with exception handling capabilities.
JavaScript implements the try...catch...finally and  construct as well as the
throw operator to handle exceptions.

You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

Here is the try...catch...finally block syntax:

<script type="text/javascript">

try {
    // Code to implement
    break;
} catch ( e ) {
    // Code to implement if an exception occurs
    break;
} finally {
    // Code that is always executed regardless of
    // an exception occurring
}

</script>

Example :

<script>
function myFunction()
{
   var val = 100;
 
   try {
      alert("Value of variable a is : " + val );
   }catch ( e ) {
      alert("Error: " + e.description );
   }finally {
      alert("Finally block will always execute!" );
   }
}
</script>

Monday, 17 February 2014

Understanding DOM (Document Object Model)

DOM stands for - Document Object Model

A Document object represents the HTML document that is displayed in a web page.
The Document object has various properties that refer to other objects which allow
access to and modification of document content.

The way that document content is accessed and modified is called the
Document Object Model, or DOM. The Objects are organized in a hierarchy.
This hierarchical structure applies to the organization of objects in a Web document.

It provides a structured representation of the document (a tree) and it defines a way
that the structure can be accessed from programs.it connects web pages to scripts or
programming languages.

Window object: Top of the hierarchy. It is the outermost element of the DOM hierarchy.

Document object: Each HTML document that gets loaded inside a window becomes a
document object. The document contains the content of the page.

Here is a simple hierarchy of few important objects:

Top most part ----------------------
HTML DOM
bottom most part

So, if you want to access button you have to load form and then only 
you can do stuffs on button , same for text and checkboxes

Wednesday, 12 February 2014

Basics of Regular Expressions

A regular expression is an object that explains a pattern of characters.

The JavaScript RegExp class represents regular expressions, and both
String and RegExp define methods that use regular expressions.
To perform pattern-matching and search-and-replace functions on text we use
Regular expressions

Syntax:
A regular expression could be defined with the RegExp( ) constructor like this:

var pattern = new RegExp(pattern, attributes);
OR
var pattern = /pattern/attributes;
Here is the description of the parameters:

pattern: A string that specifies the pattern of the regular expression or
           another regular expression.

attributes: An optional string containing any of the "g", "i", and "m" attributes
              that specify global, case-insensitive, and multiline matches, respectively.

[...]Any one character between the brackets.
[^...]Any one character not between the brackets.
[0-9]It matches any decimal digit from 0 through 9.
[a-z]It matches any character from lowercase a through lowercase z.
[A-Z]It matches any character from uppercase A through uppercase Z.
[a-Z]It matches any character from lowercase a through uppercase Z.

Examples :
<html>
<body>
<p id="demo">Click the button to do a case-insensitive search for "India" in a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "Visit India";
var patt1 = /India/i;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script>
</body>
</html>

<html>
<body>
Global pattern Matching:
Pattern value is added with "/g" which denotes global

Example:
<p id="demo">Click the button to do a global search for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "Is this all there is?";
var patt1 = /is/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script>
</body>

</html>

Wednesday, 5 February 2014

Working with Objects


Objects are made of attributes. If an attribute contains a function,
then we considered it is a method of the object otherwise, the attribute is considered a property.

The syntax for adding a property to an object is:

objectName.objectProperty = propertyValue;
Example:

var str = document.title;

Object Methods:

The methods are functions that tell the object do something or let something
be done to it. There is little difference between a function and a method,
except that a function is a standalone unit of statements and a method is
attached to an object and can be referenced by the this keyword.

Methods are useful for everything from displaying the contents of the object
to the screen to performing any complex mathematical operations on properties and parameters.

Example:

document.write("This is test");

User-Defined Objects:

All user-defined objects and built-in objects are composed of an object.

The new Operator:

The new operator is used to create an instance of an object. To create an object,
the new operator is followed by the constructor method.

In the following example, we see the constructor methods are Object(), Array(), and Date().
These constructors are built-in JavaScript functions.

var employee = new Object();
var books = new Array("C", "Perl", "Javascript");
var day = new Date("August 15, 1947");

The Object() Constructor:

A constructor is a function that creates and initializes an object.
JavaScript provides a special constructor function called Object() to build
the object. The return value of the Object() constructor is assigned to a variable.

The variable contains a reference to the new object. The properties assigned
to the object are not variables and are not defined with the var keyword.

Example 1:
create an object:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object();   // Creating the object
    book.subject = "Perl"; // Assign properties to the object
    book.author  = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
   document.write("Book name is : " + book.subject + "<br>");
   document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>

Example 2:

Creating an object with a User-Defined Function.
Here this keyword is used to refer to the object that has been passed to a function:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
    this.title = title;
    this.author  = author;
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "Mohtashim");
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>

Defining Methods for an Object:

Example:

Here is a simple example to show how to add a function along with an object:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method
function addPrice(amount){
    this.price = amount;
}

function book(title, author){
    this.title = title;
    this.author  = author;
    this.addPrice = addPrice; // Assign that method as property.
}

</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "c++");
   myBook.addPrice(100);
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
   document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>

The with Keyword:

The with keyword is used as a kind of shorthand for referencing an
object's properties or methods.

The object specified as an argument to with becomes the default object
for the duration of the block that follows. The properties and methods
for the object can be used without naming the object.

Syntax:

with (object){
    properties used without the object name and dot
}
Example:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method
function addPrice(amount){
    with(this){
       price = amount;
    }
}
function book(title, author){
    this.title = title;
    this.author  = author;
    this.price = 0;
    this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "c++");
   myBook.addPrice(100);
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
   document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Abhishek Sinha

Monday, 27 January 2014

Javascript : Classes and Objects

The Class

JavaScript is basically prototype-based language which have no class statement,
as found in C++ or Java. This is actually confusing for programmers
accustomed to languages with a class statement. In reality, JavaScript uses
functions as classes. Defining a class is as easy as defining a function.

Examples:

function employee() { }

The Objects

Objects are basically instance of classes which help us to access the methods
of that class.

To create a new instance of an object obj we use the statement new obj,
assigning the result (which will be type obj) to a variable to access it later.

In the example below we define a class named employee and we
create two instances (emp1 and emp2).

function employee() { }
var emp1= new employee();
var emp2= new employee();