Browse DevX
Sign up for e-mail newsletters from DevX


Introduction to JavaScript and DHTML : Page 2

JavaScript is a simple yet powerful feature found in most mainstream browsers. You can implement advanced features in your browser applications without round trips to the server. In this article I'll explore what JavaScript/DHTML is capable of and explain when you should use it and why.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Introduction to JavaScript and Style Sheets
As a first example using JavaScript I've created a simple menu that binds behavior to the mouse using events from the DOM. This example also introduces the topic of style sheets.

HTML supports various properties such as height, width, font color, and often borders. You can set properties directly in HTML or you can use style definitions, which you'll find are similar to styles in Microsoft Word and they're easy to reuse. Using styles has become so prevalent in browsers that they have become the desirable way to set the look and feel. Styles have even been expanded so that they offer more options than are available in HTML itself.

You can specify a style in many ways the following methods are all equivalent ways to set the font and color of a tag:

(a) Attributes of a tag

<FONT Name="ARIAL" color="BLUE">Hello World</FONT>

(b) Inline style properties

<SPAN Style="FONT-FAMILY:Arial; COLOR:Blue"> Hello World</SPAN>

(c) Referenced style tag properties

<STYLE> .MyStyle { FONT-FAMILY:Arial; COLOR:Blue} </STYLE> <SPAN Class="MyStyle">Hello World</SPAN>

Style sheets provide a way to define groups of styles for your Web page. You can make them specific to certain tag names and you can apply them automatically or you can make them generic and apply them to any tag explicitly. You can include these definitions in a Web page itself using the style tag or in a separate .css file. In the latter case you can link them to the primary Web page by including a LINK tag as follows:

<HTML> <HEAD> <LINK src="MyStyleSheet.css"> </HEAD> <BODY> <SPAN class="CurrentOption">Home</SPAN> <SPAN>Place Order</SPAN> <SPAN>FAQ</SPAN> ... </BODY> </HTML>

For example, to automatically set all SPAN tags in the page above to have a black border around them you could add the following to your style sheet:

.SPAN { BORDER: 1px; BORDER-COLOR: black; }

To be specific, a tag has to declare itself with a particular class. For example, the Home button uses the Style class named CurrentOption as follows:

.CurrentOption { BORDER: 2px; BORDER-COLOR: red; }

You can make very robust style sheets. They can include multiple levels of hierarchy and filtering. A wide variety of properties are available for you to set by using styles, including positioning, borders, fills, fonts, colors, and more.

JavaScript as a Programming Language.
JavaScript is a weakly typed scripted language that is case sensitive and built mainly of objects and functions. Objects come in three basic types: built in variable types, Web page document object model components, and custom JavaScript objects that you can build.


Variables in JavaScript are actually pointers to objects. You do not need to create common variable type objects with the NEW keyword because you can assign values with no additional syntax. Think of their value as their default property. Notice that the var bFound = false; declaration line in the program below creates and initializes the bFound object and sets its value to false, whereas the var i; line merely has a value of undefined. All of these built in types have type-specific methods that you can access as in the case of the bFound.toString() that does a type conversion and returns a string object.


Some special JavaScript core objects are static and always available. Think of these objects as the function libraries of JavaScript as they group many useful functions for easy use. For example, you can use the Math.random() method (used later in the whiteboard example) to generate a random number.

You can build your own objects using containment. These objects require creation using the NEW keyword and I'll cover them later in the whiteboard example.


Another key concept in JavaScript is the function. If you don't specify a return value, JavaScript treats the function as a void function. In the following example the function receives two parameters, a string and a comma-delimited list. Local variables get defined and will have the value null until an assignment happens. The Split function is a very useful function since JavaScript does not allow you to pass an indeterminate number of parameters. Often a delimited list can replace the need to pass and manage arrays.

Consider the following short program that contains the basic concepts comprising JavaScript:

// given a string and a comment delimited list, // determine if the string is found in the list // items and return true or false as a string function isInList(pString, pList) { // declare variables var List; var i; var bFound = false; // turn delimited string into an array List = split(pList, ","); // loop through all array positions for (i=0; I<List.length; I++) { if (pString == List[i]) { // found the string bFound = true; } } // return the answer as a string return bFound.toString(); }

You can insert comments into your code by using the double back slash '//' syntax, which tells JavaScript to ignore the rest of the line. Curly braces '{}' indicate a statement that contains code blocks. Functions and declarations use the parentheses '()'. All actual statements require an ending semi colon ';'.

Now that we've explored a basic JavaScript function, I'll show you how to use functions and bind them to events in a Web page. You can use JavaScript in many places in your pages, and when Web pages run across script they may assume that your code block is JavaScript. However, it is a far better practice to be explicit. Consider the following examples that show how to bind a simple alert MessageBox to an event.

(a) Overloading an anchor tag to do something other than linking. (The 'void' in the line ensures that the page does not refresh or attempt to navigate):

<A HREF="javascript: void alert(2+2);"> The sum of 2+2</A>

(b) Inline directly on the tag:

<SPAN OnClick="javascript:alert(3+3);"> The sum of 3 + 3</A>

(c) Script bound to an event through the script tag attributes:

<DIV Name="MyDiv">The sum of 4 + 4<.DIV> <SCRIPT language="JavaScript" for=MyDiv event="click"> alert(4+4); </SCRIPT>

(d) Inline script calling a generally available function:

<SCRIPT language="JavaScript"> function showSum() { alert(5+5) ; } </SCRIPT> <P onclick="showSum();"></P>

Behind the scenes in each of these examples the JavaScript is turned into a function and then referenced to handle the event. What may not be apparent is that these functions are (in a way) objects in JavaScript themselves and you can pass them to other functions by using their name without parentheses.

Example 1 - Simple Menu
Listing 1 demonstrates how to create a simple menu composed of a table with each cell linked to a new page. Hovering your mouse pointer over a menu item changes its color and clicking the menu item reveals a message box that specifies where it might be linked to if this was a real application.

You can use stylesheet properties and simple JavaScript events to control the look, feel, and actions of the menu. Note how I've separated the layout, styles, and scripts for clarity. This does not need to be the case, however, and the page will function the same if you specify the various pieces inline on the table and cell tags.

Listing 1 defines the menu as a table of three buttons. The styles explicitly reference the table cell elements (TDs) and provide the default colors. As various mouse events occur in each cell, you can change the colors by assigning the MenuOptionHover class and then returning to the MenuOptionNormal class. Attributes not specified in a replacing style do not get overwritten such, as the align attribute in the normal menu option style.

If you bind the scripts to the MouseOver, MouseOut, and Click events of the Table tag, the changes only occur if they detect that the event has bubbled up from a table cell element (TD). This bubbling goes from the control generating the event through its containing parent tags all the way up to the document and you can handle them at any level. You can even cancel an event so that it does not continue to bubble up. One benefit of handling events this way is that you don't have to change the code when you want to add a menu option.

Additionally, the Web page DOM is an open schema and even though the table cell (TD) tag does not support a jumpto attribute natively you can still specify it in HTML and use JavaScript to read/write it. It does not automatically acquire any special handling.

Of course you can use the jumpto (or whatever you decide to call such an attribute) to perform window.navigate so the user doesn't see an alert box.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date