JavaScript, jQuery, and DOM model interaction

Slashdot it! Delicious Share on Facebook Tweet! Digg!
Lead Image © radiantskies, 123RF.com

Lead Image © radiantskies, 123RF.com

Consider the Object

The JavaScript language has developed into an important programming language. We explain the basics and provide examples for accessing an open HTML page through the DOM interface.

With most web applications and dynamic websites, the program logic is on the server. A program written in PHP, Java, Python, or Perl generates HTML pages tailored to user requests. However, the browser itself includes a complete and very powerful run-time environment with its JavaScript interpreter.

JavaScript programs respond to user input and access the opened HTML page via a so-called DOM API. This interface between JavaScript and HTML lets you change attributes for each tag on the page, such as color, size, or visibility. It also lets you remove sections of a page or insert HTML elements anywhere (Figure 1).

Figure 1: The JavaScript run-time environment, which communicates via the DOM interface with the HTML page in both directions, responds to user input, such as mouse clicks, and modifies content and HTML tag properties.

Old Friends

Apart from being object oriented, JavaScript is very similar to the C programming language and shares many of the basic structures (loops, conditions, operators) of other languages, from Java to Perl. That's what makes the switchover so easy, as long as you use only the given procedural elements of the language that arrange the source code into routines to satisfy specific tasks.

You can avoid object orientation for smaller applications. However, JavaScript has some idiosyncrasies when it comes to larger programs in which object orientation is indispensable. The next part of this article is dedicated to its special variant of encapsulating data and inheritance.

The choice of the name JavaScript has more marketing than technical origins. Apart from a base inventory, which Java shares with C and other languages, JavaScript adopts only the dot notation object.attribute from its big brother. Unlike Java, JavaScript is not a strictly object-oriented language.

Also, JavaScript integrates elements of functional programming that Java lacks to this day. Functional programming languages can define nameless variable-bound functions (anonymous, or lambda, functions) that can also be used as function parameters. You can find a complete overview of the JavaScript language apart from its object-oriented aspect on the web [1].

Help Requested

Hardly any programmer still speaks directly to the DOM API. Its implementation differs too much from browser to browser, although the number of differences have been steadily decreasing in recent years. Additionally, it is often seen as cumbersome and bulky. Thus, most programmers use the jQuery [2] library as an interim layer. This introductory article focuses exclusively on that approach.

The first sample program uses a loop to add four colored boxes to an empty page. As an example of interactivity, clicking one box opens a dialog with text depending on its color. The lines in Listing 1 already show many of the foundations of JavaScript programming, and Figure 2 shows the result.

Listing 1

Four Interactive Boxes

01 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
02 <script type="text/javascript">
03 $(function(){ //execute when page is completed
04   var colors = ["red", "green", "blue", "yellow"];
05   var names = ["Red", "Green", "Blue", "Yellow"];
06   var sayings = {
07     "Red":"Roses are red...",
08     "Green":"A hedge between keeps friendship green.",
09     "Blue":"... violets are blue.",
10     "Yellow":"The face of cowardice is yellow."
11   };
12
13   for (var i in colors){
14     var div = $("<div>");
15     div.css({"height":"50px", "width":"150px", "background-color":colors[i]});
16     div.addClass("colorbox");
17     div.html(names[i]);
18     $("body").append(div);
19   }
20
21   $(".colorbox").on("click", function(){
22     var clicked = $(this);
23     var color = clicked.text();
24     alert(sayings[color]);
25   });
26 });
27 </script>
Figure 2: The browser writes with JavaScript what looks like simple, static content onto a blank page. Clicking a color brings up a matching text pop up.

Line 1 pulls in the jQuery library used for manipulating HTML code. If the <script> tag includes a src attribute, it references an external JavaScript file. In this case, it points to the URL of Google's version of jQuery, which saves having to download the library. The second <script> tag contains no attributes but embeds the entire program code. The type="text/javascript (line 2) references the embedded script's language.

Buy this article as PDF

Express-Checkout as PDF

Pages: 6

Price $0.99
(incl. VAT)

Buy Ubuntu User

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content