Friday, 8 August 2008

Beginning JavaScript By Paul Wilton and Jeremy McPeak

Just now i completed reading Beginning JavaScript By Paul Wilton and Jeremy McPeak

Nice book written by Paul Wilton and Jeremy McPeak.I really liked the examples which gave better idea.

I wanted to share few important points i found from this book

1) JavaScript is an interpreted language, rather than a compiled language.computer doesn’t really understand JavaScript at all. It needs something to interpret the JavaScript code and convert it into something that it understands; hence it is an interpreted language. Computers understand only machine code, which is essentially a string of binary numbers (that is, a string of zeros and ones). As the browser goes through the JavaScript, it passes it to a special program called an interpreter, which converts the JavaScript to the machine code your computer understands. It’s a bit like having a translator to translate English into Spanish, for example. The important point to note is that the conversion of the JavaScript happens at the time the code is run; it has to be repeated every time this happens. JavaScript is not the only interpreted language; there are others,
including VBScript.

2) In fact, the JavaScript language first became available in the web browser Netscape Navigator 2. Initially,it was called LiveScript. However, because Java was the hot technology of the time, Netscape decided that JavaScript sounded more exciting. When JavaScript really took off, Microsoft decided to add its own
brand of JavaScript, called JScript, to Internet Explorer. Since then, Netscape, Microsoft, and others have released improved versions and included them in their latest browsers.

3) Basically the job of a web server is to hold lots of web pages on its hard drive. When a browser, usually on a different computer, requests a web page contained on that web server, the web server loads it from its own hard drive and then passes the page back to the requesting computer via a special communications protocol called Hypertext Transfer Protocol (HTTP). The computer running the web browser that makes the request is known as the client. Think of the client/server relationship as a bit like a customer/shopkeeper relationship. The customer goes into a shop and says, “Give me one of those.” The shopkeeper serves the customer by reaching for the item requested and passing it back to the customer. In a web situation, the client machine running the web browser is like the customer, and the web server providing the page requested is like the shopkeeper.

4) The fromCharCode() Method—Converting Character Codes to a String

The method fromCharCode() can be thought of as the opposite of charCodeAt(), in that you pass it a series of comma-separated numbers representing character codes, and it converts them to a single string.

However, the fromCharCode() method is unusual in that it’s a static method—you don’t need to have created a String object to use it with, it’s always available to you.

For example, the following lines put the string “ABC” into the variable myString:

var myString;
myString = String.fromCharCode(65,66,67);


5) JavaScript Classes

A class consists of three things:
A constructor
Method definitions
Properties

The first thing you need to do is create the class constructor.


function CustomerBooking (bookingId, customerName, film, showDate)
{
this.customerName = customerName;
this.bookingId = bookingId;
this.showDate = showDate;
this.film = film;
}


When you look at the code, the important thing to note is that the constructor function’s name must match that of the class you are defining—in this case the CustomerBooking class. That way, when a new instance of your class as an object (termed an object instance) is created, this function will be called automatically. Note that you have four parameters for your constructor function, and that these are used inside the class itself. However, note that you use the this keyword. For example:

this.customerName = customerName;

Inside a constructor function or within a class method, the this keyword will refer to that object instance of your class. Here you refer to the customerName property of this class object, and you set it to equal the customerName parameter. If you have used other object-oriented programming languages,you might wonder where you defined this customerName property. The answer is that you didn’t; simply by assigning a property a value, JavaScript creates it for you. There is no check that the property exists; JavaScript creates it as it needs to. The same is true if you use the object with a property never mentioned in your class definition. All this free property creation might sound great, but it has drawbacks,the main one being that JavaScript won’t tell you if you accidentally misspell a property name;it’ll just create a new property with the misspelled name, something that can make it difficult to track bugs. One way around this problem is to create methods that get a property’s value and enable you to set a property’s value. Now this may sound like hard work, but it can reduce bugs or at least make them easier to spot. Let’s create a few property get/set methods for the CustomerBooking class.


CustomerBooking.prototype.getCustomerName = function()
{
return this.customerName;
}
CustomerBooking.prototype.setCustomerName = function(customerName)
{
this.customerName = customerName;
}
CustomerBooking.prototype.getShowDate = function()
{
return this.showDate;
}
CustomerBooking.prototype.setShowDate = function(showDate)
{
this.showDate = showDate;
}
CustomerBooking.prototype.getFilm = function()
{
return this.film;
}
CustomerBooking.prototype.setFilm = function(film)
{
this.film = film;
}
CustomerBooking.prototype.getBookingId = function()
{
return this.bookingId;
}
CustomerBooking.prototype.setBookingId = function(bookingId)
{
this.bookingId = bookingId;
}


Now you have defined a set and get method for each of your class’s four properties: bookingId, film,customerName, and showDate. Let’s look at how you created one of the methods, the getCustomerName() method.


CustomerBooking.prototype.getCustomerName = function()
{
return this.customerName;
}


Complete Example of the usage of prototype


<html>
<body>

<h2>Summary of bookings</h2>

<script language="JavaScript" type="text/javascript">

// CustomerBooking class

function CustomerBooking(bookingId, customerName, film, showDate)
{
this.customerName = customerName;
this.bookingId = bookingId;
this.showDate = showDate;
this.film = film;
}

CustomerBooking.prototype.getCustomerName = function()
{
return this.customerName;
}

CustomerBooking.prototype.setCustomerName = function(customerName)
{
this.customerName = customerName;
}

CustomerBooking.prototype.getShowDate = function()
{
return this.showDate;
}

CustomerBooking.prototype.setShowDate = function(showDate)
{
this.showDate = showDate;
}

CustomerBooking.prototype.getFilm = function()
{
return this.film;
}

CustomerBooking.prototype.setFilm = function(film)
{
this.film = film;
}

CustomerBooking.prototype.getBookingId = function()
{
return this.bookingId;
}

CustomerBooking.prototype.setBookingId = function(bookingId)
{
this.bookingId = bookingId;
}

// cinema class

function cinema()
{
this.bookings = new Array();
}

cinema.prototype.addBooking = function(bookingId, customerName, film, showDate)
{
this.bookings[bookingId] = new CustomerBooking(bookingId,
customerName, film, showDate);
}


cinema.prototype.getBookingsTable = function()
{
var booking;
var bookingsTableHTML = "<table border=1>";

for (booking in this.bookings)
{
bookingsTableHTML += "<tr><td>";
bookingsTableHTML += this.bookings[booking].getBookingId();
bookingsTableHTML += "</td>";

bookingsTableHTML += "<td>";
bookingsTableHTML += this.bookings[booking].getCustomerName();
bookingsTableHTML += "</td>";

bookingsTableHTML += "<td>";
bookingsTableHTML += this.bookings[booking].getFilm();
bookingsTableHTML += "</td>";

bookingsTableHTML += "<td>";
bookingsTableHTML += this.bookings[booking].getShowDate();
bookingsTableHTML += "</td>";
bookingsTableHTML += "</tr>";
}
bookingsTableHTML += "</table>";
return bookingsTableHTML;
}

var londonOdeon = new cinema();
londonOdeon.addBooking(342, "Arnold Palmer","Toy Story", "15 July 2009 20:15");
londonOdeon.addBooking(335, "Louise Anderson",
"The Shawshank Redemption", "27 July 2009 11:25");
londonOdeon.addBooking(566, "Catherine Hughes",
"Never Say Never", "27 July 2009 17:55");
londonOdeon.addBooking(324, "Beci Smith","Shrek", "29 July 2009 20:15");


document.write(londonOdeon.getBookingsTable());


</script>

</body>
</html>





6) JavaScript is object-based—it represents things, such as strings, dates, and arrays, using the concept of objects.

No Script at All

Sometimes people switch off JavaScript in their browsers, or use a browser that doesn’t support JavaScript, though that’s quite rare these days. To cover this situation, you can use the

<noscript>
tag. Any HTML inside the

<noscript>
tag will be displayed only to browsers that don’t support JavaScript or on which JavaScript has been disabled:


<html>
<body>
<noscript>
This website requires JavaScript to be enabled.
</noscript>
</body>
<html>


7) Example and Explanation of a Regular Expression


function regExpIs_valid(text)
{
var myRegExp = /[^a-z\d ]/i;
return !(myRegExp.test(text));
}


The function takes just one parameter: the text you want to check for validity. You then declare a variable,myRegExp, and set it to a new regular expression, which implicitly creates a new RegExp object. The regular expression itself is fairly simple, but first let’s think about what pattern you are looking for.
What you want to find out is whether your passphrase string contains any characters that are not letters between A and Z or between a and z, numbers between 0 and 9, or spaces. Let’s see how this translates into a regular expression.

First you use square brackets with the ^ symbol.
[^]

This means you want to match any character that is not one of the characters specified inside the square brackets. Next you add a-z, which specifies any character in the range a through z.
[^a-z]

So far your regular expression matches any character that is not between a and z. Note that, because you added the i to the end of the expression definition, you’ve made the pattern case-insensitive. So our regular expression actually matches any character not between A and Z or a and z.

Next you add \d to indicate any digit character, or any character between 0 and 9.
[^a-z\d]

So your expression matches any character that is not between a and z, A and Z, or 0 and 9. Finally, you decide that a space is valid, so you add that inside the square brackets.
[^a-z\d ]

Putting this all together, you have a regular expression that will match any character that is not a letter, a digit, or a space

8) The srcElement Property

Another valuable piece of information offered by the event object is the srcElement property. This property retrieves the HTML element that receives the event. For example, consider the following

HTML:


<a href=”somePage.htm” onclick=”alert(‘Hello! You clicked me!’)”>Click Me</a>


When you click this link, an alert box displays the message Hello! You clicked me! That’s obvious,right? What may not be so obvious is what actually receives the click event: the

<a/>
element. If you were to check the srcElement property during this event, it would point to this particular

<a/>
element.This information is particularly useful when you need to manipulate the element that received the event.


<!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>Using the srcElement Property</title>

<script type="text/javascript">
function image_eventHandler() {
var sourceElement = window.event.srcElement; //Get the element.
var eventType = window.event.type; //Get the type of event.

if (eventType == "mouseover") { //The mouse rolled over the image.
sourceElement.src = "o.gif"; //So change the image's src property.
}

if (eventType == "mouseout") { //The mouse moved out.
sourceElement.src = "x.gif"; //So change it back to the original picture.
}
}
</script>
</head>
<body>
<img src="x.gif" onmouseover="image_eventHandler()" onmouseout="image_eventHandler()" />
</body>
</html>



9) Below example gives one implementation of Cross-Browser Image Rollover.


<!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>Cross-browser Image Rollover</title>

<script type="text/javascript">
function image_eventHandler(evt) {
var elementTarget;
if (evt.srcElement) { //The browser is IE
elementTarget = evt.srcElement;
} else { //The browser is non-IE
elementTarget = evt.target;
}

if (evt.type == "mouseover") { //The mouse rolled over the image.
elementTarget.src = "o.gif"; //So change the image's src property.
}

if (evt.type == "mouseout") { //The mouse moved out.
elementTarget.src = "x.gif"; //So change it back to the original picture.
}
}
</script>
</head>
<body>
<img src="x.gif" onmouseover="image_eventHandler(event)" onmouseout="image_eventHandler(event)" />
</body>
</html>



10) Base DOM Objects

Three objects, shown in the following table, are known as the base DOM objects.






ObjectDescription
NodeEach node in the document has its own Node object
NodeListThis is a list of Node objects
NamedNodeMapThis provides access by name rather than by index to all the Node objects


11) Create HTML Elements and Text with DOM JavaScript

You’ll create a web page with just paragraph

<p/>
and heading

<h1/>
elements, but instead of HTML you’ll use the DOM properties and methods to place these elements on the web page.

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>Creating Nodes</title>
</head>
<body>
<script type=”text/javascript”>
var newText = document.createTextNode(“My Heading”);
var newElem = document.createElement(“h1”);
newElem.appendChild(newText);
document.body.appendChild(newElem);
newText = document.createTextNode(“This is some text in a paragraph”);
newElem = document.createElement(“p”);
newElem.appendChild(newText);
document.body.appendChild(newElem);
</script>
</body>
</html


12) The DOM Event Model

The standard outlines several properties and methods of the event object that have long since been a source of dispute between IE and other browsers.










Properties of the event ObjectDescription
bubblesIndicates whether an event can bubble (pass control from one element to another)
cancelableIndicates whether an event can have its default action canceled
currentTargetIndicates which event is currently being processed
eventPhaseIndicates which phase of the event flow an event is in
target (DOM browsers only)Indicates which element caused the event; in the
DOM event model, text nodes are the possible target of an event
typeIndicates the name of the event


13) Creating a toolbar is easy; however, there is one caveat you must consider. Since you generate the HTML elements dynamically and append them to document.body, you must create the toolbar while the document is loading, or after the document is loaded. If you attempt to load the toolbar at any other time,you’ll get errors in your page.

Example:


<html>
<head>
<title>IE Toolbar</title>
<style type="text/css">
.toolbar
{
background-color: #E4E2D5;
padding: 3px;
}

.toolbar div
{
display: inline;
height: 24px;
width: 24px;
}

.toolbar-button
{
padding: 3px;
}

.toolbar-button-hover
{
border: 1px solid #316AC5;
background-color: #C1D2EE;
padding: 2px;
cursor: hand;
}

.toolbar-icon
{
height: 24px;
width: 24px;
}
</style>
<script type="text/javascript">
function button_mouseover() {
var eSrc = window.event.srcElement;

if (eSrc.className == "toolbar-button") {
eSrc.className = "toolbar-button-hover";
}
}

function button_mouseout() {
var eSrc = window.event.srcElement;
var toSrc = window.event.toElement;

if (eSrc.className == "toolbar-button-hover" && toSrc.tagName != "IMG") {
eSrc.className = "toolbar-button";
}
}

function button_click() {
var eSrc = window.event.srcElement;

if (eSrc.tagName == "IMG") {
eSrc = eSrc.parentNode;
}

eSrc.className = "toolbar-button";
window.location.href = eSrc.getAttribute("href");
}

function createToolbar(sName, aButtons) {
var toolbar = document.createElement("div");
toolbar.id = sName;
toolbar.className = "toolbar";


for (var i = 0; i < aButtons.length; i++) {
var thisButton = aButtons[i];

var button = document.createElement("div");
var icon = document.createElement("img");

button.setAttribute("href", thisButton[1]);
button.className = "toolbar-button";

button.onclick = button_click;
button.onmouseover = button_mouseover;
button.onmouseout = button_mouseout;

icon.src = thisButton[0];
icon.className = "toolbar-icon";

button.appendChild(icon);
toolbar.appendChild(button);
}

document.body.appendChild(toolbar);
}

var myToolbar = new Array();

myToolbar[0] = new Array();
myToolbar[0][0] = "img/green.gif";
myToolbar[0][1] = "javascript: alert('You Clicked the Green Button!')";

myToolbar[1] = new Array();
myToolbar[1][0] = "img/blue.gif";
myToolbar[1][1] = "javascript: alert('You Clicked the Blue Button!')";

myToolbar[2] = new Array();
myToolbar[2][0] = "img/red.gif";
myToolbar[2][1] = "http://www.wrox.com";
</script>

</head>
<body onload="createToolbar('myToolbar', myToolbar)">

</body>
</html>



Hope you enjoy reading this book

About the Author

Paul Wilton started as a Visual Basic applications programmer at the Ministry of Defense in the UK, then found himself pulled into the Net. Having joined an Intermet development company, he spent three years helping create Internet solutions. He's now running his own successful and rapidly growing company developing online holiday property reservation systems.

Jeremy McPeak began tinkering with web development as a hobby in 1998. Currently working in IT department of a school district, Jeremy has experience developing web solutions with JavaScript, PHP, and C#. He has written several online articles covering topics such as XSLT, WebForms, and C#. He is also co-author of Professional Ajax

No comments: