devxlogo

Introduction to JavaScript and DHTML

Introduction to JavaScript and DHTML

avaScript is a powerful yet often underused feature of most browser-based applications. Commonly, JavaScript is relegated to simple form validations, but this is not the only capability of JavaScript. In this article I’ll cover a powerful set of features you can incorporate in your applications today.

This article explores the following examples:

  • A simple menu system.
  • A scrollable data grid complete with column headers and row selection.
  • A whiteboard using VML that shows how to create simple classes in JavaScript.

The examples (created in Internet Explorer) assume a basic familiarity with HTML. Please note that this article is an overview of JavaScript and DHTML, and except for a brief discussion of .NET, does not really address JavaScript’s place in the creation of .NET User Controls.

What Are JavaScript and DHTML and What Can They Do?
Put simply, JavaScript is a no frills and yet flexible programming language supported by all major Web browsers. Although it is supported on most Web servers, and performs server-side processing that creates a Web page you can send to a browser, its real power comes from using it to manipulate the HTML of a Web page in a client browser environment.

The browser exposes the structure of a Web page to JavaScript through a document object model or DOM. You typically refer to programming the DOM using JavaScript as using Dynamic Hyper Text Markup Language (DHTML).

Since the DOM exposes the current Web page as an object hierarchy of the pieces in the document, you can use JavaScript to manipulate its parts. If you want a section of the page to disappear for a while, find its representative object in the hierarchy and set its style visibility property to hidden. Later on you can set it back to visible. If you want to have a bouncing ball on the screen, add a new HTML IMG element, showing the ball, to the object hierarchy and reposition it every second using whatever function you want to specify for the bouncing behavior. If you want to handle a collection of items without worrying about binding events to each one, wait for events to bubble up from child to parent in the DOM hierarchy and handle them at the container level.

You can easily handle all these tasks more by using JavaScript and DHTML. In fact, JavaScript also allows you to create simple class objects, and you can reuse your favorite pieces of client-side code.

Quick Recap of the Web Server/Web Page Cycle.
JavaScript is very good at manipulating Web pages, however, Macromedia Flash or server-side code may be a better choice if you have a lot to manipulate. Since every application is different, there are no global rules, but a quick discussion of the structure of a Web page may help you understand where the blocks and difficulties will appear in your own applications.

Figure 1 shows the simplified logical architecture of the cycle for a Web browser to request and send information .to a Web Server.

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

   Hello World

(b) Inline style properties

      Hello World

(c) Referenced style tag properties

      Hello World

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:

                                Home       Place Order       FAQ       ...        

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

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.

Objects

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.

Functions

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

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):

      The sum of 2+2

(b) Inline directly on the tag:

      The sum of 3 + 3

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

   
The sum of 4 + 4<.DIV>

(d) Inline script calling a generally available function:

      

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.

Programming the Web Page Document Object Model (DOM)
In the case of the Web page Document Object Model, consider that some functions related to the browser itself, such as navigating to new pages and handling the recently navigated history, must be available to JavaScript. An object called the Navigator, which represents the root object and the browser itself, commonly exposes these functions. Always available, the navigator is never defined by the content the user loads.

The Navigator creates instances of a Window class that holds and contains Web page documents. The Window class has its own set of functionality such as the parent coordinates of the window itself and the Web page document loading status. As the parent to the document, it also provides the event handling and events from the document that bubble up to the Window object, but can end up trapped there by application developers embedding Web browsers in their desktop programs.

Figure 2: A major browser and Web page objects.

Whereas the Navigator and instances of Window objects are predefined, a document object hierarchy can look different for every Web page although it conforms to a particular allowable DOM schema. Put plainly, the document is a hierarchy of the objects that make up the page and changes to it can directly change how a page looks and acts. The document hierarchy for a page gets created as a page loads into the browser and gets parsed, but you can modify the document hierarchy through script at any time. Web pages that do not conform to the allowable HTML syntax of the DOM will yield unexpected results. By default, a browser ignores badly formed HTML. As a result, these "bad" pieces never show in the document for that page.

Although, the DOM is fairly well standardized by the W3C and the major browsers attempt to adhere to it, there are still some differences, especially with the newer features so consult your target browser's documentation. Figure 2 shows an overview of the more important objects available in the Internet Explorer DOM.

Note: Not all HTML tags or all objects available in the object model are included in Figure 2. Please refer to your browser documentation for complete details.

Example 2 ? A Better Data Grid, the WebGrid
The example I've created in this section expands on some of the concepts from the first example and shows how you can use the DOM to modify a page at runtime. In this case the page loads a scrollable table with some data and lets the user select a row with both hover and selected row functionality.

Figure 3 shows the WebGrid in action. As you can see, it is possible to make elements on a Web page look like a conventional Windows user interface.

Creating Your Own Objects
One of the nicest features of JavaScript is that you can create your own object classes. They do have limitations such as not being inheritable, but they can contain and manage other objects as well as having properties and methods.

An Object class has a Constructor function that creates the object by adding all properties and methods to it. JavaScript inherits the basic Object() and hands it to the constructor as the 'this' variable. Your constructor then can add properties and methods using this.x = 100;, and this.toString = myFunction; syntax as desired. Your constructor can then return the 'this' variable and the calling function gets an instance of the class.

The technique of adding methods into an object may not be immediately apparent. All functions when defined are prototypes objects. To be exposed as a method on an object they need to be set to a property on the object by using the address of the function prototype instead of the result. Basically, this is the difference between using myFunction and myFunction(x,y).

There is a problem though, because JavaScript does not know that you intend a particular function for a given object. Nor does JavaScript distinguish between functions of the same name in different .js files to be different. Therefore if JavaScript runs across a myPrint function it may overwrite a previous myPrint function from a different file.

The solution depends on your desired effect. In the case where you'll never use the function or it won't have visibility anywhere but in the particular class, you can nest the function within the constructor. This is perfectly valid JavaScript syntax and defines the scope of the function prototype as only being within the constructor function. The second technique is to define the functions with a naming convention so that their names are always unique. This alternate method allows reuse of the function and inclusion in other objects since its prototype has public scope.

Using Existing Objects in HTML, VML, VRML, XML, etc.
The basic purpose of the browser is to present a Web page to the user. In the first generation of browsers that meant exclusively HTML, which not only presented text and images but allowed a developer to specify the layout as well. As browsers and the Web matured, several other layout languages have emerged to handle more than just text and images.

VML in particular was created to handle drawing lines and symbols and associated tasks such as gradient fills and shading and so forth. This new language has its own tags beyond HTML that are interpreted by the browser and expose different functions and behaviors.

While VML presents a rich two-dimensional toolkit to the Web designer, VRML presents a whole three-dimensional world modeling system where tags refer to shapes, light sources, and viewing angles.

And even while those examples expand the browser in new ways, XML as a simple and very HTML-like structure is also handled and presented with a collapsible and color-coded hierarchy.

As a taste of how far you can go very easily using the browser, and also to show how creating your own objects can simplify coding, the following example creates an object to manage a whiteboard of VML lines as examples in Figure 4.

See also  Comparing different methods of testing your Infrastructure-as-Code
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist

©2024 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.