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

var keyword JavaScript

The var and function are declaration statements—they declare
or define variables and functions. These statements define
identifiers (variable and function names) that can be used elsewhere
in your program and assign values to those identifiers.
Declaration statements don’t do much themselves, but by creating
variables and functions they, in an important sense,


Expression Statements

Assignment statements are one major category of
expression statements.
 For example:


Function Call Spacing

Almost universally, the recommended style for function calls is to have no space between
the function name and the opening parenthesis, which is done to differentiate it
from a block statement. For example:


The try-catch Statement

JavaScript provides a try-catch statement that is capable of intercepting thrown errors
before they are handled by the browser. The code that might cause an error comes in
the try block and code that handles the error goes into the catch block. For instance:

try {
somethingThatMightCauseAnError();
} catch (ex) {
handleError(ex);
}


JavaScript Object Literals

Object literals are a popular way to create new objects with a specific set of properties,
as opposed to explicitly creating a new instance of Object and then adding properties.
For example, this pattern is rarely used:

JavaScript Refresh Page

you refresh the page using document.location.reload(). You can add the true keyword to force the reloaded page to come from the server (instead of cache). Alternatively, you can use the false keyword to reload the page from the cache.

Creating Elements, Attributes, and Objects

An important benefit of dynamic content is the ability to create new content from
freshly received data. This is necessary in dynamic menu creation, navigation, breadcrumbs,

JavaScript Form Validation

 JavaScript Form Validation. JavaScript can be used to validate data in HTML forms


<script type="text/javascript">
function validate_all()
    {
    var frmReg=document.manageadmin;
  
  
  
    if(frmReg.name.value.search(/\S/) == -1)
        {
            alert("Please enter name.");
            frmReg.name.focus();
            return false;
        }
  
  
    if(frmReg.textEmail.value.search(/\S/) == -1)
        {
            alert("Please enter Email.");
            frmReg.textEmail.focus();
            return false;
        }
  

Embedding Content for Plug-Ins

Although never officially a part of any HTML specification, the <<embed>> tag is most often used to include embedded objects for Netscape and Internet Explorer. A Macromedia Flash file might be embedded as follows:
 
 
<<embed id="demo" name="demo"
 src="http://www.javascriptref.com/examples/ch18/flash.swf"
 width="318" height="252" play="true" loop="false"
 pluginspage="http://www.macromedia.com/go/getflashplayer"
 swliveconnect="true">><</embed>>
 
The most important attributes of the <<embed>> tag are src, which gives the URL of the embedded object, and pluginspage, which indicates to the browser where the required plug-in is to be found if it is not installed in the browser. Plug-in vendors typically make available the embedding syntax, so check their site for the value of pluginspage.
Recall that applets embedded with <<object>> tags are passed initial parameters in <<param>> tags. The syntax of <<embed>> is different in that initial parameters are passed using attributes of the element itself. For instance, in the preceding example the play attribute tells the plug-in to immediately begin playing the specified file.
The <<object>> element is the newer, official way to include embedded objects of any kind in your pages. However, <<object>> is not supported in Netscape browsers prior to version 4, and <<embed>> continues to be supported by new browsers. So it is unlikely that <<object>> will completely supplant <<embed>> any time in the near future.
 

Remote JavaScript

The primary reason is that the round trip time required to submit a form and then download the response is often inconvenient. The user experience is much improved if, instead of clicking a Submit button and watching the screen go blank and then be replaced by the response of a server-side program, a user can click a button and have the page be updated without a visible form submission. To the user, the page would behave more like an application than a Web page. 

There are other advantages as well. If communication with a server can be done behind the scenes instead of using form submissions or clicking on links, the developer can carry out more complicated tasks requiring multiple server requests at once. The ability to use remote JavaScript also means that tasks that previously required an ActiveX object or Java applet can be implemented with script. This is a tremendous timesaver for the developer and also reduces the complexity of debugging significantly. 

The abstraction that remote JavaScript brings to life is the remote procedure call. A remote procedure call (RPC) is a function that executes on a remote machine, in this case a Web server. The client, in this case our browser using JavaScript, passes arguments to the “function” it wishes to call via an HTTP request; the server executes the specified function, often implemented as a CGI program or server-side script in PHP or a similar language, and returns the results as the body of the HTTP response. It’s important to remember that while JavaScript is used to make the function call and often to handle the return value, the function itself executes on the server, and therefore can be implemented as a CGI, PHP script, Java servlet, or using any other technology a Web server might have available.

JavaScript Dynamic Links and Menus

Many sites use JavaScript to create links to other website pages. Here is some example
code with different link types that you may want to avoid:

<HTML>
<head>
<title>Link Examples ~ Things to stay away from</title>
<script type="text/javascript">
function gotoLocationX(){
window.location.href='http://www.cnn.com';
}
function gotoLocationY(){
window.location.href='http://www.yahoo.com';
}
function gotoLocationZ(){
window.location.href='http://www.google.com';
}
</script>
</head>
<body>

Example 1:
<a href="#" onClick="javascript:window.location.href=
'http://www.cnn.com'">News on CNN</a>
<br><br>
Example 2:
<a href="#" onClick="javascript:gotoLocationY()">Yahoo Portal</a>
<br><br>
Example 3:
<form>
<input name="mybtn" value="Google Search Engine" type=button
onClick="window.location.href='http://www.google.com'">
</form>
<br><br>
</body>
</html>

When you open this code in your browser, you will see a screen similar to Figure 8-2.
This is not to say that you can never use dynamic links. You obviously can, but you
need to think about tweaking your code to help web spiders see what they need to see.

Javascript Math object

The Math object holds a set of constants and methods enabling more complex mathematical operations than the basic arithmetic operators

var root = Math.sqrt(10);


Constants Provided by the Math Object
Property
Description
Math.E
The base of the natural logarithm (Euler's constant e)
Math.LN2
Natural log of 2
Math.LN10
Natural log of 10
Math.LOG2E
Log (base 2) of e
Math.LOG10E
Log (base 10) of e
Math.PI
Pi (p)
Math.SQRT1_2
Square root of 0.5 (equivalently, one over the square root of 2)
Math.SQRT2
Square root of 2
Table 7-4: Methods Provided by the Math Object
Method
Returns
Math.abs(arg)
Absolute value of arg
Math.acos(arg)
Arc cosine of arg
Math.asin(arg)
Arc sine of arg
Math.atan(arg)
Arc tangent of arg
Math.atan2(y, x)
Angle between the x axis and the point (x, y), measured counterclockwise (like polar coordinates). Note how y is passed as the first argument rather than the second.
Math.ceil(arg)
Ceiling of arg (smallest integer greater than or equal to arg)
Math.cos(arg)
Cosine of arg
Math.exp(arg)
e to arg power
Math.floor(arg)
Floor of arg (greatest integer less than or equal to arg)
Math.log(arg)
Natural log of arg (log base e of arg)
Math.max(arg1, arg2)
The greater of arg1 or arg2
Math.min(arg1, arg2)
The lesser of arg1 or arg2
Math.pow(arg1, arg2)
arg1 to the arg2 power
Math.random()
A random number in the interval [0,1]
Math.round(arg)
The result of rounding arg to the nearest integer. If the decimal portion of arg is greater than or equal to .5, it is rounded up. Otherwise, arg is rounded down.
Math.sin(arg)
Sine of arg
Math.sqrt(arg)
Square root of arg
Math.tan(arg)
Tangent of arg
There are several aspects of the Math object that need to be kept in mind. The trigonometric methods work in radians, so you need to multiply any degree measurements by p / 180 before using them. Also, because of the imprecise characteristic of floating-point operations, you might notice minor deviations from the results you expect. For example, though the sine of p is 0, the following code:
alert(Math.sin(Math.PI));

JavaScript and XML

To demonstrate JavaScript, XML, and the DOM in action, let’s use Internet Explorer 5.5 or better to load an XML document containing our employee directory and see if we can manipulate it. First, to load in the document we create an instantiation of Microsoft’s XML parser using the JScript-specific ActiveXobject. Once the object is created, we load the appropriate XML document into memory. In this case, it is the pure XML file of employee records we saw earlier without style sheets or other references.
var xmldoc = new ActiveXObject("Microsoft.XMLDOM");

xmldoc.async = false;

xmldoc.load("staff2.xml");
Once loaded, we can then use the DOM to manipulate it. For example, we can access the root element of the document (<<directory>>) using
var rootElement = xmldoc.documentElement;
then we might alert out its nodeName property as shown in this example.
<<!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>>XML Demo<</title>>

<<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />>

<</head>>

<<body>>

<<script type="text/jscript">>

<<!--

 var xmldoc = new ActiveXObject("Microsoft.XMLDOM");

 xmldoc.async = false;

 xmldoc.load("staff.xml");



 var rootElement = xmldoc.documentElement;

//-->>

<</script>>

<<form action="#" method="get">>

 <<input type="button" value="show node"

 onclick="alert(rootElement.nodeName);" />>

<</form>>

<</body>>

<</html>>
 
 
 
 
 
 
function deleteLastElement()

{

  var rootElement = xmldoc.documentElement;

  if (rootElement.hasChildNodes())

     rootElement.removeChild(rootElement.lastChild);

}
 
 
 
Really the only difference here is the use of the xmldoc object we created to reference the XML document rather than just plain document, which would reference the HTML Document object. Otherwise, the manipulations are the same as with HTML.
 

Javascript Image Objects

Properties of Image Objects
Property
Description
align
Indicates the alignment of the image, usually “left” or “right.”
alt
The alternative text rendering for the image as set by the alt attribute.
border
The width of the border around the image in pixels.
complete
Non-standard (but well-supported) Boolean indicating whether the image has completed loading.
height
The height of the image in pixels or as a percentage value.
hspace
The horizontal space around the image in pixels.
isMap
Boolean value indicating presence of the ismap attribute, which indicates the image is a server-side image map. The useMap property is used more often today.
longDesc
The value of the (X)HTML longdesc attribute, which provides a more verbose description for the image than the alt attribute.
lowSrc
The URL of the “low source” image as set by the lowsrc attribute. Under early browsers, this is specified by the lowsrc property.
name
The value of the name attribute for the image.
src
The URL of the image.
useMap
The URL of the client-side image map if the <img> tag has a usemap attribute.
vspace
The vertical space in pixels around the image.
width
The width of the image in pixels or as a percentage value.
The traditional Image object also supports onabort, onerror, and onload event handlers. The onabort handler is invoked when the user aborts the loading of the image, usually by clicking the browser’s Stop button. The onerror handler is fired when an error occurs during image loading. The onload handler is, of course, fired once the image has loaded. Under modern browser implementations that support (X)HTML properly, you will also find onmouseover, onmouseout, onclick, and the rest of the core events supported for Image.

Javascript The + Operator

The binary + operator adds numeric operands or concatenates string operands:

1 + 2 // => 3
"hello" + " " + "there" // => "hello there"
"1" + "2" // => "12"

When the values of both operands are numbers, or are both strings, then it is obvious
what the + operator does. In any other case, however, type conversion is necessary, and
the operation to be performed depends on the conversion performed. The conversions
rules for + give priority to string concatenation: if either of the operands is a string or
an object that converts to a string, the other operand is converted to a string and concatenation
is performed.

Javascript Recursion

Recursion is when a function calls itself. This is often useful in mathematics,
such as fi nding the nth number in the Fibonacci series (1, 2, 3, 5,
8, 13, 21…).
function fi bonacci(n) {
if ( n < 2 ) {
return 1;
} else {
return fi bonacci(n-2) + fi bonacci(n-1);
}
}
fi bonacci(5);
8
fi bonacci(10);
89

Javascript Objects as Arguments

You may want to write functions that take many arguments, some of
which are optional.
function drawElement( color, border, width, height,
left, top, zIndex) {
// Make and display an element with these variables
}
drawElement("red", 4, null, null, 100, 10);
Function signatures like this aren’t ideal for a couple of reasons:
■ It’s hard to remember the exact order of arguments.
■ You have to specify null values when you want to use the default
value for arguments in the middle of the signature.
■ Did you notice that I forgot to specify a value for zIndex? It’s hard to
count all those arguments correctly!
Passing multiple values in a single object is often a better solution:
function drawElement(options) {
// Make and display an element with the values in options
}
drawElement({
color: "red",
border: 4,
left: 100,
top: 10
});
Specifying default values is a little bit trickier with this technique. You’ll
need to create an object holding all the defaults and merge it with the
options object.

Javascript search

search(regexp)
The search() method is the same as indexOf() except that it takes a
regular expression pattern instead of a substring. It also returns -1 if the
pattern isn’t found.
"hello world".search(/[aeiou]/); // Find the fi rst vowel
1
"hello world".search(/\d/); // Find the fi rst digit
-1
match(regexp)
The match() method returns an array containing all the substrings
matching the regular expression and its subpatterns. Unlike the other
search-and-replace methods, it returns null if the pattern doesn’t match.
Here are some simple examples, but I’ll cover this function more in
Chapter 8:
// Find all the vowels
"hello world".match(/[aeiou]/g);
["e", "o", "o"]
// Find "world" regardless of capitalization
"hElLo WoRlD".match(/world/i);
["WoRlD"]
replace(pattern, replacement)
The replace() method works like match() except that it returns a string
with all instances of pattern replaced by the string replacement.
// Remove all non-numeric characters from a phone number
"(310) 555-9876".replace(/\D/g, "");

JavaScript Popups

<head>
<script type="text/javascript">

function testPopup() {
window.open( "http://www.google.com/" )
}

</script>
</head>
<body>
<form>
<input type="button" onClick="testPopup()" value="Click">
</form>
</body>


OpenNewWindow =window.open('contact.html','help','toolbar=no,
location=0,directories=no,status=yes,menubar
=0,scrollbars=yes,resizable=yes,
width=300,height=350')





JavaScript Window.Open Arguments


When you open a window, you can set its URL, name, size, buttons, and other attributes, such as whether or not the window can be resized. The basic syntax of this method is


window.open(url, name, features, replace)


where

url is a URL that indicates the document to load into the window.

name is the name for the window (which is useful for referencing later on using the target attribute of HTML links).features is a comma-delimited string that lists the features of the window.

replace is an optional Boolean value (true or false) that indicates if the URL specified should replace the window’s contents or not. This would apply to a window that was already created.

An example of this method is

secondwindow = open("http://www.yahoo.com", "yahoo", "height=300,width=200,

 scrollbars=yes");



<a href="http://www.google.com" target="_blank">Go to Google</a>

Javascript Making a simple MouseOver

<a href="http://www.cit.cornell.edu"
onMouseOver="document.logo.src='family.gif ' ; "
onMouseOut ="document.logo.src='harry.gif ' ; " >
<img name="logo" src="harry.gif " border=0></a>


The onMouseOver and onMouseOut attributes are “Event Handlers” that tell the browser what
code to execute when the events occur. You can make it so that the mouseover affects another image on
the page by changing the name of the image accordingly in the event handler code.

We can use a MouseOver to animate a still image when the
mouse rolls over it. In your class files folder you have two images, logoscroll.gif and logostill.gif which
can be used to create this effect.