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

Array Indexing-javascript

Array Indexing
Arrays in JScript are sparse. That is, if you have an array with three elements that are numbered 0, 1, and 2, you can create element 50 without worrying about elements 3 through 49. If the array has an automatic length variable (see Intrinsic Objects for an explanation of automatic monitoring of array length), the length variable is set to 51, rather than to 4. You can certainly create arrays in which there are no gaps in the numbering of elements, but you aren't required to. In fact, in JScript, your arrays don't have to have numbered subscripts at all. In JScript, objects and arrays are essentially identical to each other. The real difference is not in the data, but rather in the way you address the members of an array or the properties and methods of an object.
Addressing Arrays
There are two main ways to address the members of an array. Ordinarily, you address arrays by using brackets. The brackets enclose either a numeric value or an expression that evaluates to a nonnegative integer. The following example assumes that the entryNum variable is defined and assigned a value elsewhere in the script.
theListing = addressBook[entryNum];
theFirstLine = theListing[1];
This method of addressing is equivalent to the method for addressing objects, though in object addressing, what follows the period must be the name of an actual property. If there is no such property, your code generates an error. The second way to address an array is to make an object/array that contains properties that are numbered, and then generate the numbers in a loop. The following example generates two arrays, one for the name and one for the address, from a listing in addressBook. Each of these contains four properties. An instance of theName, for example, built from the [Name1] through [Name4] properties of theListing, might contain "G." "Edward" "Heatherington" "IV", or "George" "" "Sand" "".
theListing = addressBook[entryNum];
for (i = 1; i < 4; i++)  {
theName[i] = theListing["Name" + i];
theAddress[i] = theListing["Address" + i];
}
While this particular instance is short, and could easily have been written in the "dot" style of notation,that is, addressing theListing, theName, and theAddress as objects rather than as arrays, that is not always possible. Sometimes the particular property may not exist until run time, or there may be no way to know which one it will be in advance. For example, if the addressBook array were arranged by last name instead of by numbered listings, the user would probably be entering names "on the fly," while the script is running, to look people up. The following example assumes the existence of appropriate function definitions elsewhere in the script.
theListing = addressBook[getName()];
theIndivListing = theListing[getFirstName()];
This is associative addressing of the array, that is, addressing by means of fully arbitrary strings.

javascript Variable Scope

Microsoft JScript has two scopes: global and local. If you declare a variable outside of any function definition, it is a global variable, and its value is accessible and modifiable throughout your program. If you declare a variable inside of a function definition, that variable is local. It is created and destroyed every time the function is executed; it cannot be accessed by anything outside the function.
A local variable can have the same name as a global variable, but it is entirely distinct and separate. Consequently, changing the value of one variable has no effect on the other. Inside the function in which the local variable is declared, only the local version has meaning.
var aCentaur = "a horse with rider,";  // Global definition of aCentaur.

// JScript code, omitted for brevity.
function antiquities()  // A local aCentaur variable is declared in this function.
{

// JScript code, omitted for brevity.
var aCentaur = "A centaur is probably a mounted Scythian warrior";

// JScript code, omitted for brevity.
  aCentaur += ", misreported; that is, ";  // Adds to the local variable.

// JScript code, omitted for brevity.
}  // End of the function.

var nothinginparticular = antiquities();
aCentaur += " as seen from a distance by a naive innocent.";

/*
Within the function, the variable contains "A centaur is probably a mounted Scythian warrior,
misreported; that is, "; outside the function, the variable contains the rest of the sentence:
"a horse with rider, as seen from a distance by a naive innocent."
*/  
It's important to note that variables act as if they were declared at the beginning of whatever scope they exist in. Sometimes this results in unexpected behaviors.
var aNumber = 100;
var withAdditive = 0;

withAdditive += aNumber;  // withAdditive is now 100.
tweak();
withAdditive += aNumber;  // withAdditive is now 200.

function tweak()  {
var newThing = 0;  // Explicit declaration of the newThing variable.
// The next statement, if it were not commented out, would generate an error.
// newThing = aNumber;
// The next statement assigns the value 42 to the local aNumber, implicitly declaring it.
aNumber = 42;
if (false)  {
    var aNumber;  // This statement is never executed.
    aNumber = "Hello!";  // This statement is never executed.
    }  // End of the conditional.
}  // End of the function definition.
The statement that is commented out attempts to assign the value of the local variable aNumber to the local variable newThing. It fails, despite the fact that a local aNumber variable is defined elsewhere in the function, and therefore exists throughout. The aNumber variable does not have any assigned value at the point where this statement occurs in the code

Javascript Calendar script


Javascript Calendar script


<style type="text/css">

.main {
width:200px;
border:1px solid black;
}

.month {
background-color:black;
font:bold 12px verdana;
color:white;
}

.daysofweek {
background-color:gray;
font:bold 12px verdana;
color:white;
}

.days {
font-size: 12px;
font-family:verdana;
color:black;
background-color: lightyellow;
padding: 2px;
}

.days #today{
font-weight: bold;
color: red;
}

</style>
<script type="text/javascript">
function buildCal(m, y, cM, cH, cDW, cD, brdr){
var mn=['January','February','March','April','May','June','July','August','September','October','November','December'];
var dim=[31,0,31,30,31,30,31,31,30,31,30,31];

var oD = new Date(y, m-1, 1); //DD replaced line to fix date bug when current day is 31st
oD.od=oD.getDay()+1; //DD replaced line to fix date bug when current day is 31st

var todaydate=new Date() //DD added
var scanfortoday=(y==todaydate.getFullYear() && m==todaydate.getMonth()+1)? todaydate.getDate() : 0 //DD added

dim[1]=(((oD.getFullYear()%100!=0)&&(oD.getFullYear()%4==0))||(oD.getFullYear()%400==0))?29:28;
var t='<div class="'+cM+'"><table class="'+cM+'" cols="7" cellpadding="0" border="'+brdr+'" cellspacing="0"><tr align="center">';
t+='<td colspan="7" align="center" class="'+cH+'">'+mn[m-1]+' - '+y+'</td></tr><tr align="center">';
for(s=0;s<7;s++)t+='<td class="'+cDW+'">'+"SMTWTFS".substr(s,1)+'</td>';
t+='</tr><tr align="center">';
for(i=1;i<=42;i++){
var x=((i-oD.od>=0)&&(i-oD.od<dim[m-1]))? i-oD.od+1 : '&nbsp;';
if (x==scanfortoday) //DD added
x='<span id="today">'+x+'</span>' //DD added
t+='<td class="'+cD+'">'+x+'</td>';
if(((i)%7==0)&&(i<36))t+='</tr><tr align="center">';
}
return t+='</tr></table></div>';
}

</script>

<script type="text/javascript">

var todaydate=new Date()
var curmonth=todaydate.getMonth()+1 //get current month (1-12)
var curyear=todaydate.getFullYear() //get current year

document.write(buildCal(curmonth ,curyear, "main", "month", "daysofweek", "days", 1));
</script>

buildCal(4, 2003, "main", "month", "daysofweek", "days", 0)

Validate Email address

 

Checking Email 


Web sites often use email addresses as usernames because they are guaranteed to be unique, as long as they are valid. In addition, the organizations can use the email addresses to communicate with their users later. You do not have to initiate a server round trip just to validate an email address, however. This task can be initiated in the client, which cancels the submission of the username to the server if the email syntax is invalid.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head> <script type="text/javascript" src="js/http_request.js"></script> 
<script type="text/javascript" src="js/email.js"></script>
 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
<title>Enter email</title>
 </head> <body> 
<form action="javascript:void%200">
 <div id="message"></div>
 Enter email: <input type="text" name="email" size="25"> 
<br /> <button type="submit" name="submit" value="Send">Send</button>
 </form> </body> </html>



This function creates a new Email object, validates the user's email address,
 and, if it's valid, submits it to a server component.
Let's take a closer look at the checkAddress( ) function:
function checkAddress(val){
    var eml = new Email(val);
    var url;
    eml.validate(  );
    if (! eml.valid) {eMsg(eml.message,"red")};
    if(eml.valid)
    {
        url="http://www.parkerriver.com/s/checker?email="+
            encodeURIComponent(val);
        httpRequest("GET",url,true,handleResponse);
    }
}



var user,domain, regex, _match;

window.onload=function(  ){
    document.forms[0].onsubmit=function(  ) {
        checkAddress(this.email.value);
        return false;
    };
};
/* Define an Email constructor */
function Email(e){
    this.emailAddr=e;
    this.message="";
    this.valid=false;
}

function validate(  ){
    //do a basic check for null, zero-length string, ".", "@",
    //and the absence of spaces
    if (this.emailAddr == null || this.emailAddr.length == 0 ||
    this.emailAddr.indexOf(".") == -1 ||
    this.emailAddr.indexOf("@") == -1 ||
    this.emailAddr.indexOf(" ") != -1){
    this.message="Make sure the email address does " +
    "not contain any spaces "+
    "and is otherwise valid (e.g., contains the \\"commercial at\\" @ sign).";
        this.valid=false;
        return;
    }

    /* The local part cannot begin or end with a "."
    Regular expression specifies: the group of characters before the @    
    symbol must be made up of at least two word characters, followed by zero   
    or one period char, followed by at least 2 word characters. */
    regex=/(^\\w{2,}\\.?\\w{2,})@/;
    _match = regex.exec(this.emailAddr);

    if ( _match){
        user=RegExp.$1;
        //alert("user: "+user);
    } else {
       this.message="Make sure the user name is more than two characters, "+
            "does not begin or end with a period (.), or is not otherwise "+
            "invalid!";
        this.valid=false;
        return;
    }
    //get the domain after the @ char
    //first take care of domain literals like @[19.25.0.1], however rare
    regex=/@(\\[\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}.\\d{1,3}\\])$/;
    _match = regex.exec(this.emailAddr);

    if( _match){
        domain=RegExp.$1;
        this.valid=true;
    } else {
/* The @ character followed by at least two chars that are not a period (.),
followed by a period, followed by zero or one instances of two or more
characters ending with a period, followed by two-three chars that are 
not periods */
        regex=/@(\\w{2,}\\.(\\w{2,}\\.)?[a-zA-Z]{2,3})$/;
        _match = regex.exec(this.emailAddr);
        if( _match){
            domain=RegExp.$1;
           //alert("domain: "+domain);
        } else {
            this.message="The domain portion of the email had less than 2 
                         chars "+
                         "or was otherwise invalid!";
            this.valid=false;
            return;
        }
    }//end domain check
    this.valid=true;

}

//make validate(  ) an instance method of the Email object
Email.prototype.validate=validate;

function eMsg(msg,sColor){
    var div = document.getElementById("message");
    div.style.color=sColor;
    div.style.fontSize="0.9em";
    //remove old messages
    if(div.hasChildNodes(  )){
        div.removeChild(div.firstChild);
    }
    div.appendChild(document.createTextNode(msg));

}
//a pull-it-all-together function
function checkAddress(val){
    var eml = new Email(val);
    var url;
    eml.validate(  );
    if (! eml.valid) {eMsg(eml.message,"red")};
    if(eml.valid)
    {
        //www.parkerriver.com
        url="http://www.parkerriver.com/s/checker?email="+
            encodeURIComponent(val);
        httpRequest("GET",url,true,handleResponse);
    }
}
//event handler for XMLHttpRequest
//see Hack #24
function handleResponse(  ){
    //snipped...
}

First, the code sets up the handling for the user's click on the Send button. window.onload specifies an event handler that is called when the browser completes the loading of the web page:
window.onload=function(  ){
    document.forms[0].onsubmit=function(  ) {
        checkAddress(this.email.value);
        return false;
    };
};

Validate a Text Field


No web developers want their Ajax applications to hit the network with requests if the users leave necessary text fields blank. Thus, checking that input elements of type text and the large boxes called textareas in HTML contain values is one of the most common forms of validation.
This hack shows the code for checking if a text control is blank. The inline way of doing this is by assigning a check for the field's value in the text field's event handler:
 
<input type="text" name="firstname" id="tfield" onblur=
"if (this.value) {doSomething(  );}" />

or in the textarea's event handler:
<textarea name="tarea" rows="20" id="question" cols="20" onblur=
"if (this.value) {doSomething(  );}">

The JavaScript phrase if (this.value) {...} returns false if the user leaves a field blank, so the function call doSomething( ) will never occur. JavaScript evaluates a blank web-form text field as the empty string or "", which evaluates to false when it's used in the context of a programming test. The this keyword is a nice generic way of referring to the form field that contains the event handler attribute.

Probably a better way of going about your event-handling tasks is to separate the logic of your code from the HTML or template text that comprises the application's visual aspects. The JavaScript goes into an external file that the HTML page imports with a script tag. Inside the external file, the code binds a field's various event handlers to a function or the code that represents your application's behavior.
Let's take the following web page, myapp.html, which includes the following HTML in its header:
 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="js/hacks_method.js"></script>
    <title>Cool Ajax application</title>
</head>

The file hacks_method.js is located in a directory js, which is in the same directory as the HTML file. The HTML file contains the same textarea and text field as mentioned earlier, except these fields no longer have an onblur attribute. The JavaScript file includes this code:
 
window.onload=function(  ){
    var txtA = document.getElementById("tarea");
    if(txtA != null){
        txtA.onblur=function(  ){
            if (this.value) { doSomething(  );}
        };
    }
    var tfd = document.getElementById("tfield");
    /* An alternative:
    if(tfd != null && txtA != null){tfd.onblur = txtA.onblur; }
    */
    if(tfd != null){
        tfd.onblur=function(  ){
            if (this.value) { doSomething(  );}
        };
    }
}

window.onload involves the binding of the load event to your blank-field checks. load occurs when the browser has completed loading the web page, so when that happens, all the stuff after window.onload= follows.
The getElementById( ) method returns a reference to an HTML element

PHP and Javascript Variables

Variables

To define a variable in PHP, you’d write:
// PHP
$n = 1;
The equivalent in JavaScript is:
// JavaScript
var n = 1;

There’s no dollar sign, just the name of the variable.
 Like in PHP, you don’t define variable
types because the type is derived from the value.
 You use varfor all types.

If you need a numeric type, you give your variable a
 numeric value. The same applies
to booleans and strings:

var n = 1;  // number
var b = true;  // boolean
var s = "hello"; // string

You have the option of declaring a variable without
 initializing it with a value. In such cases, the variable
 is assigned the special value undefined:
var a;
a; // `a` has the special value `undefined`

Redeclaring an existing variable doesn’t set the variable
 value back to undefined:

var a = 1;
var a;
// `a` is still 1

You can declare and optionally initialize with a
 value several variables with one var statement as
 long as you separate them with a comma and
 end with a semicolon:

var pi = 3.14,
yeps = true,
nopes,
hi = "hello",
wrrrld = "world";

Technically, var is optional. But unless the variable
 was defined higher up in the scope chain , if youskip
 var, you end up with a global variable.

And you’ve learned, prob‐ably the hard way, that
 global namespace pollution is a sin. Additionally,
there are some subtle differences if you declare
 a global variable with and without var.

To cut a long story short, resist this temptation and
always use varto declare your variables.

Detecting JavaScript and Cookie Compatibility

You may be expecting a huge dump of code to see if JavaScript and cookies are enabled. There ’ s no way
that you ’ d want to go through with something like that at this point in the project, so the following
minimalist code is offered as a decent check for JavaScript compatibility:
< noscript >
You will not be able to view this site if JavaScript is not enabled.
Please turn on JavaScript to use this site.
< /noscript >

 all you need to put in your template view, and you ’ re 100 percent covered. If they don ’ t
have JavaScript turned on, they get this message. There really is no way to test to see if JavaScript is
turned on (after all, if it is off, you can ’ t run a test to see if it is on.
if (true){
//do something here, we must be on
}else{
//well shucks, JavaScript turned off, there’s no way to send an error message!
}

The  < noscript > option is very straightforward and displays just the error message. You might want to
add some branding to it, like the Claudia ’ s Kids logo, maybe a phone number or other information, but
that ’ s about as good as it gets. You could also contemplate removing the AJAX handlers from the
shopping carts, but that seems a bit much.

The same thing goes when checking for cookie support. You ’ ll need just a small bit of code that will try
to set a test cookie with a value say, the integer 1. If the site can write the cookie and retrieve it OK, then
cookies are supported. If not, display an error message.

< script >
var tcookie = new Date();
check_cookie = (tcookie.getTime() + ‘’);
document.cookie = “check_cookie=” + check_cookie + “; path=/”;
if (document.cookie.indexOf(check_cookie,0) < 0) {
alert(“You will not be able to view this site if cookies are not enabled.
Please enable them now.”);
}

< /script >

Javascript Array

Creating an Object

We have already seen an example of an Array object being created. To create an Array object, we used the JavaScript statement
var myArray = new Array();
So how is this statement made up?
The first half of the statement is familiar to us. We use the var keyword to define a variable called myArray. This variable is initialized, using the assignment operator (=), to the right-hand side of the statement.
The right-hand side of the statement consists of two parts. First we have the keyword new. This tells JavaScript that we want to create a new object. Next we have Array(). This is the constructor for an Array object. It tells JavaScript what type of object we want to create. Most objects have constructors like this. For example, the Date object has the Date() constructor.


we can pass parameters to the constructor Array() to add data to our object. For example, to create an Array object that has three elements containing the data "Paul", "Paula", and "Pauline", we use
var myArray = new Array("Paul", "Paula", "Pauline");
Let's see some more examples, this time using the Date object. The simplest way of creating a Date object is
var myDate = new Date();
This will create a Date object containing the date and time that it was created. However,
var myDate = new Date("1 Jan 2000");
will create a Date object containing the date 1 January 2000.
How object data is stored in variables differs from how primitive data, such as text and numbers, is stored. (Primitive data is the most basic data possible in JavaScript.) With primitive data, the variable holds the data's actual value. For example
var myNumber = 23;
means that the variable myNumber will hold the data 23. However, variables assigned to objects don't hold the actual data, but rather a reference to the memory address where the data can be found. This doesn't mean we can get hold of the memory address—this is something only JavaScript has details of and keeps to itself in the background. All you need to remember is that when we say that a variable references an object, this is what we mean. We show this in the following example:
var myArrayRef = new Array(0, 1, 2);
var mySecondArrayRef = myArrayRef;
myArrayRef[0] = 100;
alert(mySecondArrayRef[0]);
First we set variable myArrayRef reference to the new array object, and then we set mySecondArrayRef to the same reference—for example, now mySecondArrayRef is set to reference the same array object. So when we set the first element of the array to 100 as shown here:
myArrayRef [0] = 100;
and display the contents of the first element of the array referenced in mySecondArrayRef as follows:
alert(mySecondArrayRef[0])
we'll see it also magically has changed to 100! However, as we now know, it's not magic; it's because both variables referenced the same array object because when it comes to objects, it's a reference to the object and not the object stored in a variable. When we did the assignment, it didn't make a copy of the array object, it simply copied the reference. Contrast that with the following:
var myVariable = "ABC";
var mySecondVariable = myVariable;
myVariable = "DEF";
alert(mySecondVariable);
In this case we're dealing with a string, which is primitive data type, as are numbers. This time it's the actual data that's stored in the variable, so when we do this:
var mySecondVariable = myVariable;
mySecondVariable gets its own separate copy of the data in myVariable. So the alert at the end will still show mySecondVariable as holding "ABC."
To summarize this section, we create a JavaScript object using the following basic syntax:
var myVariable = new ObjectName(optional parameters);

Creating a Cookie-Javascript

To make life easier for ourselves, we'll write a function that allows us to create a new cookie and set certain of its attributes with more ease. We'll look at the code first and create an example using it shortly.
function setCookie(cookieName, cookieValue, cookiePath, cookieExpires)
{
   cookieValue = escape(cookieValue);
   if (cookieExpires == "")
   {
      var nowDate = new Date();
      nowDate.setMonth(nowDate.getMonth() + 6);
      cookieExpires = nowDate.toGMTString();
   }
   if (cookiePath != "")
   {
      cookiePath = ";Path=" + cookiePath;
   }
   document.cookie = cookieName + "=" + cookieValue +
      ";expires=" + cookieExpires + cookiePath;
}
The secure and domain parts of the cookie string are unlikely to be needed, so we just allow the name, value, expires, and path parts of a cookie to be set by the function. If we don't want to set a path or expiration date, we just pass empty strings for those parameters. If no path is specified, the current directory and its subdirectories will be the path. If no expiration date is set, we just assume a date six months from now.
The first line of the function introduces the escape() function, which we've not seen before.
cookieValue = escape(cookieValue);
When we talked about setting the value of a cookie, we mentioned that certain characters cannot be used directly, such as a semicolon. (This also applies to the name of the cookie.) To get around this problem, we can use the built-in escape() and unescape() functions.


alert(escape("2001 a space odyssey;"));
We can see that the spaces have been converted to %20, % indicating that they represent an escape or special character rather than an actual character, and that 20 is the ASCII value of the actual character. The semicolon has been converted to %3B, as we'd expect.
As we'll see later, when retrieving cookie values we can use the unescape() function to convert from the encoded version to plain text.
Back to our function; we next have an if statement.
   if (cookieExpires == "")
   {
      var nowDate = new Date();
      nowDate.setMonth(nowDate.getMonth() + 6);
      cookieExpires = nowDate.toGMTString();
   }
This deals with the situation where an empty string, "", has been passed for the cookieExpires parameter of the function. Because most of the time we want a cookie to last longer than the session it's created in, we set a default value for expires that is six months after the current date.
Next, if a value other than an empty string ("") has been passed to the function for the cookiePath parameter, we need to add that value when we create the cookie. We simply put "path=" in front of any value that has been passed in the cookiePath parameter.
   if (cookiePath != "")
   {
      cookiePath = ";Path=" + cookiePath;
   }
Finally on the last line we actually create the cookie, putting together the cookieName, cookieValue, cookieExpires, and cookiePath parts of the string.
   document.cookie = cookieName + "=" + cookieValue +
      ";expires=" + cookieExpires + cookiePath;
We'll be using the setCookie() function whenever we want to create a new cookie because it makes setting a cookie slightly easier than having to remember all the parts we want to set. More importantly, it can be used to set the expiration date to a date six months ahead of the current date.
For example, to use the function and set a cookie with default values for expires and path we just type the following:
setCookie("cookieName","cookieValue","","")

Javascript cookie string

We can set a cookie by setting document.cookie to a cookie string.
 The following code will set a cookie with the UserName set as Paul,
 and an expiration date of 28 December 2010.

<html>
<head>
<script language=JavaScript>
   document.cookie = "UserName=Paul;expires=Tue, 28 Dec 2010 00:00:00;";
</script>
</head>
<body>
<p>This page just created a cookie</p>
</body>
</html>

Save the page as FreshBakedCookie.htm. We'll see how the code works as we
 discuss the parts of a cookie string, but first let's see what happens
 when a cookie is created.

In this section we'll see how to look at the cookies that are already stored by IE on our computer. We'll then load the cookie-creating page we just created with the preceding code to see what effect this has.

First we need to open IE. I'm using IE 6, so if you're using IE 4 or 5 you will find the screenshots and menus in slightly different places.

Before we view the cookies, we'll first clear the temporary Internet file folder for the browser because this will make it easier to view the cookies that our browser has stored. In IE, select Internet Options from the Tools menu,




javascript Date, Time





Javascript Date

The methods getDate(), getDay(), getMonth(), and getFullYear() allow us to retrieve date values from inside a Date object. The setDate(), setMonth(), and setFullYear() methods allow us to set the date values of an existing Date object.

The getHours(), getMinutes(), getSeconds(), and getMilliseconds() methods retrieve the time values in a Date object. The setHours(), setMinutes(), setSeconds(), and setMilliseconds() methods allow us to set time values of an existing Date object.

 One thing that we didn't cover in that chapter was the idea that the time depends on your location around the world. For example, imagine you have a chat room on your website and want to organize a chat for a certain date and time. Simply stating 15:30 is not good enough if your website attracts international visitors.

The time 15:30 could be Eastern Standard Time, Pacific Standard Time, the time in the United Kingdom, or even the time in Kuala Lumpur. You could of course say 15:30 EST and let your visitors work out what that means, but even that isn't foolproof. There is an EST in Australia as well as in the U.S.


So how does this work? In the script block at the top of the page, we have just this one line:
var localTime = new Date();
This creates a new Date object and initializes it to the current date and time based on the client computer's clock. (Note that in fact the Date object simply stores the number of milliseconds between the date and time on your computer's clock and midnight UTC time on the 1st of January 1970.)
Within the body of the page we have seven more script blocks that use the three world time methods we looked at earlier. Note that some of them are enclosed in an if statement, for example
if (localTime.toLocaleTimeString)
{
  document.write(localTime.toLocaleTimeString())
}
This checks to see if the browser supports that method and only makes use of it if it does. Older browsers don't support all of the date/time methods so doing this prevents ugly errors.

In the following line
document.write(localTime.toUTCString());
we write the string returned by the toUTCString() method to the page. This converts the date and time stored inside the localTime Date object to the equivalent UTC date and time.

JavaScript Interview Questions

JavaScript Interview Questions




What is the difference between == and === ?
The == checks for value equality, but === checks for both type and value.

difference between innerHTML and append() in JavaScript?
InnerHTML is not standard, and its a String. The DOM is not, and although innerHTML is faster and less verbose, its better to use the DOM methods like appendChild(), firstChild.nodeValue, etc to alter innerHTML content.

break and continue statements?
Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current loop. 



Javascript closures?
A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.

What is Strict Mode in JavaScript?
Strict Mode has been introduced as part of ECMAScript 5 and introduces new, restricted variant of JavaScript which has following aims:
  • Throws errors for actions that are rather silly but previously didn’t throw an error
  • Throws errors for potentially unsafe actions
  • Disables functions that are poorly thought out
  • Potentially code in strict mode could run faster by eliminating mistakes that would make it difficult for JavaScript engines to perform optimizations
Is javascript case sensitive?
Yes javascript is case sensitive.
Examples are isNaN , Number, new Array().

How to set the cursor to wait ?
document.body.style.cursor = 'wait';
//do something interesting and time consuming
document.body.style.cursor = 'auto';  



What's Prototypes for JavaScript?  
Objects have "prototypes" from which they may inherit fields and functions. 

 a checkbox using Javascript?  
var checked = window.document.getElementById("thmyCheckBox").checked;
What does "5"+2+4 evaluate to?  
Since 5 is a string, everything is a string, so the result is 524.  
How to create arrays in JavaScript? 
 declare an array like this
var scripts = new Array();
We can add elements to this array like this

scripts[0] = "A";
scripts[1] = "B";
scripts[2] = "C";
scripts[3] = "D"; 
 


isNaN function?
Return true if the argument is not a number.  


GET and POST in HTML forms?
GETmethod: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb.
POST
method: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.
 


Differentiate between “var a=5” and “a =5” ?
difference is between the two is that one variable is local and the other is global.


How to get value from a textbox?

document.getElementById('txtbox1').value;

What are global variables?

Global variables are available throughout your code: That is, the variables have no scope. Local variables scope, on the other hand, is restricted to where it is declared (like within a function). The var keyword is used to declare a local variable or object, while omitting the var keyword creates a global variable.

// Declare a local variable
var localVariable = "testtest";
// Declare a global
globalVariable = "Cghdg";

What are JavaScript types?

• Number
• String
• Boolean
• Function
• Object
• Null
• Undefined

What is this keyword?

It refers to the current object.


how html Elements using javascript? 
the getElementById method is preferred.
document.getElementById("test").style.color = "green";

 


 

 


Prototypes

Every Java-
Script object has a second JavaScript object (or null, but this
is rare) associated with it. This second object is known as a
prototype, and the first object inherits properties from the
prototype.
All objects created by object literals have the same prototype
object, and we can refer to this prototype object in JavaScript
code as Object.prototype. Objects created using the new keyword
and a constructor invocation use the value of the proto
type property of the constructor function as their prototype.
So the object created by new Object() inherits from Object.pro
totype just as the object created by {} does. Similarly, the object
created by new Array() uses Array.prototype as its prototype,
and the object created by new Date() uses Date.prototype as its
prototype.
Object.prototype is one of the rare objects that has no prototype:
it does not inherit any properties. Other prototype objects
are normal objects that do have a prototype. All of the built-in
constructors (and most user-defined constructors) have a prototype
that inherits from Object.prototype.

Object.create() is a static function, not a method invoked on
individual objects. To use it, simply pass the desired prototype
object:
// o1 inherits properties x and y.
var o1 = Object.create({x:1, y:2});

JavaScript Timers

setTimeout() and setInterval() allow you to register a function
to be invoked once or repeatedly after a specified amount
of time has elapsed. These are important global functions of
client-side JavaScript, and are therefore defined as methods of
Window, but they are general-purpose functions and don’t
really have anything to do with the window.
The setTimeout() method of the Window object schedules a
function to run after a specified number of milliseconds elapses.
setTimeout() returns a value that can be passed to clear
Timeout() to cancel the execution of the scheduled function.


Retrieving the Response

A complete HTTP response consists of a status code, a set of
response headers, and a response body. These are available
through properties and methods of the XMLHttpRequest
object:
• The status and statusText properties return the HTTP
status in numeric and textual forms. These properties hold
standard HTTP values like 200 and “OK” for successful
requests, and 404 and “Not Found” for URLs that don’t
match any resource on the server.
• The response headers can be queried with getResponse
Header() and getAllResponseHeaders().
• The response body is available in textual form from the
responseText property.
The XMLHttpRequest object is used asynchronously: the
send() method returns immediately after sending the request,
and the response methods and properties listed above aren’t
valid until the response is received.

WebSocket() constructor

socket with the WebSocket() constructor:
var s = new WebSocket("ws://ws.example.com/resource");
The argument to the WebSocket() constructor is a URL that uses
the ws:// protocol (or wss:// for a secure connection like that
used by https://). The URL specifies the host to connect to,
and may also specify a port (WebSockets use the same default
ports as HTTP and HTTPS) and a path or resource.
Once you have created a socket, you generally register event
handlers on it:
s.onopen = function(e) { /* The socket is open. */ };
s.onclose = function(e) { /* The socket closed. */ };
s.onerror = function(e) { /* Something went wrong! */ };
s.onmessage = function(e) {
var m = e.data; /* The server sent a message. */
};
In order to send data to the server over the socket, you call the
send() method of the socket:
s.send("Hello, server!");
When your code is done communicating with the server, you
can close a WebSocket by calling its close() method.
WebSocket communication is completely bidirectional. Once
a WebSocket connection has been established, the client and
server can send messages to each other at any time, and that
communication does not have to take the form of requests and
responses.

concat() Method

The concat() method returns the array resulting from appending its arguments to
 the array on which it was invoked. Given the script:

JavaScript Security

Downloading and running programs written by unknown parties is a dangerous proposition. A program available on the Web could work as advertised, but then again it could also install spyware, a backdoor into your system, or a virus, or exhibit even worse behavior such as stealing or deleting your data. The decision to take the risk of running executable programs is typically explicit; you have to download the program and assert your desire to run it by confirming a dialog box or double-clicking the program’s icon. But most people don’t think about the fact that nearly every time they load a Web page, they’re doing something very similar: inviting code—in this case, JavaScript—written by an unknown party to execute on their computer. Since it would be phenomenally annoying to have to confirm your wish to run JavaScript each time you loaded a new Web page, the browser implements a security policy designed to reduce the risk such code poses to you.

Reserved Words in JavaScript

Reserved Words in JavaScript 1.5
>abstract
else
instanceof
switch
>boolean
enum
int
synchronized
>break
export
interface
this
byte
extends
long
throw
case
false
native
throws
catch
final
new
transient
char
finally
null
true
class
float
package
try
const
for
private
typeof
continue
function
protected
val
debugger
goto
public
var
default
if
return
void
delete
implements
short
volatile
do
import
static
while
double
in
super
with

HTTP “200 OK” response

A complete request is not necessarily a successful request, and
your handler for the load event should check the status code
of the XMLHttpRequest object to ensure that you received an
HTTP “200 OK” response rather than a “404 Not Found” response,