Приглашаем посетить
Брюсов (bryusov.lit-info.ru)

11.5 Some DOM Core applications

Table of Contents

Previous Next

11.5 Some DOM Core applications

11.5.1 A page to organize your photos

We will look at two DOM Core applications in this section. Our first application is a continuation of the last example, ex11-09.htm. To transform this example into a user-friendly program, we will add the following three features.

  • Pictures generated on the page can be moved freely on the page when you hold down the mouse so that photos can be organized anywhere you like.

  • A Gen. Page (generating page) button is added and when this button is clicked, a new page in a new window is generated. All the organized pictures are arranged in the designed positions. This page can then be saved to your local storage or hard drive so that you can view your photos at any time.

  • When one of the pictures inside the generated page is clicked, the full size of the image is displayed in another window.

The interface part of this example is simple and is listed as follows:



Example: ex11-10.htm - A Page To Organize Your Photos

 1:  <?xml version="1.0" encoding="iso-8859-1"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5:  <head><title>A Page To Organize Your Photos  ex1110.htm</title></head>
 6:  <style>
 7:   .butSt{background-color:#dddddd;font-family:arial;font-weight:bold;
 8:      font-size:14pt;color:#880000;width:150px;height:35px}
 9:  </style>
10:  <body style="background:#bbbbbb;font-family:arial;font-size:20pt;
11:     color:#008800;font-weight:bold;text-align:center">
12:   Inserting Images At Run Time<br />
13:
14:  <table align="center"><tr>
15:   <td><input type="text" class="butSt" value="File Name:"
16:           style="color:#000088"/></td>
17:   <td><input type="file" id="fileId" class="butSt"
18:           style="width:350px" /></td></tr><tr>
19:   <td><input type="button" onclick="myAddPic()" class="butSt"
20:          value="Insert Pic" /></td>
21:   <td><input type="button" onclick="genPage()" class="butSt"
22:          value="Gen. Page" /></td></tr>
23:  </table>
24:
25:  <img src="line1.gif" width="550" height="6" alt="pic" /><br />
26:  <div id="id02" style="color:#00ff00"></div><br />
27:
28:  <script src="ex1110.js"></script>
29:  </body>
30:  </html>

This interface is similar to that in ex11-09.htm. A Gen. Page button is added so that a Web page is generated and all pictures are imported into this new page. The source of this page can then be saved as an independent application and hence could be used as standalone page or reused in other applications.

To show this application in action, we start by generating five pictures as shown in Fig. 11.18. Once the pictures are loaded, they can be moved anywhere on the screen by clicking the picture and holding down the mouse button. This feature is simply a moving object application of Chapter 9. A simple positioning of the images is shown in Fig. 11.19.

Figure 11.18. Loading some pictures

graphics/11fig18.jpg


Figure 11.19. Positioning the images

graphics/11fig19.jpg


When you have finished with the arrangement of the images and the Gen. Page button is clicked, a new window is opened on the screen with all the desirable images and positions embedded (see Fig. 11.20). When any of the pictures of this new page is clicked, the full size of the picture is displayed in another new window (see Fig. 11.21).

Figure 11.20. Generating new page

graphics/11fig20.jpg


Figure 11.21. Some full-size pictures

graphics/11fig21.gif


If the XHTML code of this page is saved to your local hard drive by using the normal "View" and "Source" options, the page can then be reviewed again at any time.

The external program file ex11-10.js contains the code to control all actions. The first part of the program file is listed as follows:



Example: ex11-10.js - The ECMAScript For ex1110.htm (Part One)

 1:  var IE = document.all?true:false
 2:
 3:  var widthV=200
 4:  var heightV=150
 5:  var hspaceV =10
 6:  var vspaceV =10
 7:  var picV = "pic"
 8:  var objV = document.getElementById("id02")
 9:  var noPic =0
10:
11:  function myAddPic()
12:  {
13:    noPic++
14:
15:    fileV = document.getElementById("fileId").value
16:    fileVV = "file://"+fileV
17:    newImg = document.createElement("img")
18:    tmpV = newImg.setAttribute("alt","pic")
19:    imgV = "img"+noPic
20:    tmpV = newImg.setAttribute("id",imgV)
21:    tmpV = newImg.setAttribute("hspace",hspaceV)
22:    tmpV = newImg.setAttribute("vspace",vspaceV)
23:
24:  if (!IE) {
25:    tmpV = newImg.setAttribute("width",widthV)
26:    tmpV = newImg.setAttribute("height",heightV)
27:    tmpV = newImg.setAttribute("onmousedown","mouseDownEvent("+noPic+")")
28:    tmpV = newImg.setAttribute("onmouseup","mouseUpEvent()")
29:    tmpSt="position:absolute;top:"+(100+noPic*40)+"px;left:"+
30:           (40+noPic*30)+"px"
31:    tmpV = newImg.setAttribute("style",tmpSt)
32:  }
33:    tmpV = newImg.setAttribute("src",fileVV)
34:    tmpV = document.body.insertBefore(newImg,objV)
35:
36:  if (IE) {
37:    imgObj = document.getElementById(imgV)
38:    imgObj.style.width=widthV+"px"
39:    imgObj.style.height=heightV+"px"
40:    imgObj.style.position="absolute"
41:    imgObj.style.top=(100+noPic*40) +"px"
42:    imgObj.style.left=(40+noPic*30)+"px"
43:    imgObj.attachEvent("onmousedown",mouseDownEvent)
44:    imgObj.attachEvent("onmouseup",mouseUpEvent)
45:  }
46: }
47:

The first part of the program file contains one function, myAddPic(). The main purpose of this function is to generate image elements at run time. The browser detection code in line 1 is needed in order to take care of some backward compatibility issues.

From line 3 to line 22, the program is very similar to that in ex11-09.js. The aim is to create the image element <img />. Since some earlier IE browsers (including IE5.0 and IE5.5) didn't support the setAttribute() function on events such as onmousedown and onmouseup, the W3C standard statements in lines 2432 are dedicated to the NS6+ series. That is, if the browser is not IE, the W3C standard coding (lines 2531) is used to set the width, height, onmousedown, onmouseup, and style properties of the image element. After all the attribute settings, the image is inserted into the page by executing the statement in line 34.

If IE is detected, the alternative codes dedicated to the IE browser are executed in lines 3645. In order to prevent a complete overlap of images, we change the top and left position of every loaded picture (see lines 2930 and lines 4142). Launching the onmousedown and onmouseup events (lines 4344) guarantees that the pictures can move with the mouse. The code for controlling the picture and mouse movements is provided in the second part of the program ex11-10.js.



Listing: Continuation Of The ECMAScript ex1110.js (Part Two)

48: var selectObj = null
49: var working =0
50:
51: function mouseDownEvent(objId)
52: {
53:   selectObj="img"+objId
54:   if (IE) selectObj = event.srcElement.id
55: }
56:
57: function mouseUpEvent()
58: {
59:   if (selectObj != null)
60:   {
61:     working =1
62:     selectObj = null;
63:   }
64: }
65:
66: function mouseMoveEvent(e)
67: {
68:   if (selectObj != null)
69:   {
70:     if (IE)
71:     {
72:      lxPos = event.clientX
73:      lyPos = event.clientY
74:     } else {
75:      lxPos = e.pageX
76:      lyPos = e.pageY
77:     }
78:     objW = widthV
79:     objH = heightV
80:     document.getElementById(selectObj).style.left = (lxPos - objW/2) +"px"
81:     document.getElementById(selectObj).style.top = (lyPos - objH/2) +"px"
82:   }
83:  return (false)
84: }
85:
86: document.onmousemove=mouseMoveEvent
87:

In fact, this part of the program is simply a cut-down version of ex09-10.js in Chapter 9. When the left mouse button is down, this event triggers the function mouseDownEvent() to get the identity of the object held by the mouse. If IE is detected, the event.srcElement (source element) returns the identity of the picture. When the mouse button is up, the function mouseUpEvent() is called to release the object. The function mouseMoveEvent() in lines 6684 listens to every mouse movement, to capture the mouse positions and to store them in variables lxPos and lyPos. These new mouse positions are then used to move the picture.

The final part of the program contains a single function genPage(). This function is called when the Gen. Page button is pressed.



Listing: Continuation Of The ECMAScript ex1110.js (Part Three)

88: function genPage()
89: {
90:   headSt = ' <?xml version="1.0" encoding="iso-8859-1"?> \n'+
91:  ' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" \n'+
92:  ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> \n '+
93:  '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> \n'+
94:  '<head><title>Generated Page</title></head> \n'+
95:  '<body id="body" style="background:#aaaaaa;font-family:arial;'+
96:  'font-size:22pt; \n color:#000088;font-weight:bold;text-align:center">\n'+
97:       '<div> My Photo Album</div><br />'
98:   llStV =""
99:   for (jj=1;jj<document.images.length;jj++)
100:  {
101:   tmpV = document.images.item(jj).src
102:   topV = document.images.item(jj).style.top
103:   leftV = document.images.item(jj).style.left
104:   llStV = llStV+ '<a href="'+tmpV+'" target=_blank >'+
105:   '<img src="'+tmpV+'" width="'+widthV+'" height="'+heightV+'" hspace="'+
106:     hspaceV+'" vspace="'+vspaceV+
107:   '" style="position:absolute;top:'+topV+';left:'+leftV+'" /></a> \n'
108:  }
109:  winH = window.open()
110:  winH.document.open()
111:  winH.document.write(headSt+llStV+'</body></html>')
112:  winH.document.close()
113: }

Inside this function, we have a string called headSt to store a general header for the newly created page. After the header string, a for-loop is employed to get information about the pictures already on the screen. For every image on the screen the statements in lines 101107 are employed to generate an XHTML image element that looks like this:



<a href="xxPic.xx" target=_blank>
<img src="xxPic.xx" width="widthV" height="heightV"
    hspace="hspaceV" vspace="vspaceV"
    style="position:absoluate;top:topV;left:leftV" /></a>

All loaded images are stored as a string in variable llStV. The final step of the program is to perform the following tasks:

  • open a new window;

  • open a document for writing;

  • output the strings headSt, llStV, and "</body></html>" to the newly created document; and

  • close the document.

All these tasks can be accomplished by executing the four statements in lines 109112.

Again the source of this new page can be saved in your local storage and reviewed at any time. For this example, the generated page looks like the following:



Listing: ex11-10.txt - The Generated Web Page From ex1110.htm

 1:  <?xml version="1.0" encoding="iso-8859-1"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title>Generated Page</title></head>
 6: <body id="body" style="background:#aaaaaa;font-family:arial;
 7:   font-size:22pt;color:#000088;font-weight:bold;text-align:center">
 8: <div> My Photo Album</div><br />
 9: <a href="file:///P:/chap11a/01_img.jpg" target=_blank ><img
10:  src="file:///P:/chap11a/01_img.jpg" width="200" height="150" hspace="10"
11:  vspace="10" style="position:absolute;top:137px;left:113px" /></a>
12: <a href="file:///P:/chap11a/03_img.jpg" target=_blank ><img
13:  src="file:///P:/chap11a/03_img.jpg" width="200" height="150" hspace="10"
14:  vspace="10" style="position:absolute;top:135px;left:456px" /></a>
15: <a href="file:///P:/chap11a/05_img.jpg" target=_blank ><img
16:  src="file:///P:/chap11a/05_img.jpg" width="200" height="150" hspace="10"
17:  vspace="10" style="position:absolute;top:301px;left:298px" /></a>
18: <a href="file:///P:/chap11a/06_img.jpg" target=_blank ><img
19:  src="file:///P:/chap11a/06_img.jpg" width="200" height="150" hspace="10"
20:  vspace="10" style="position:absolute;top:468px;left:115px" /></a>
21: <a href="file:///P:/chap11a/07_img.jpg" target=_blank ><img
22:  src="file:///P:/chap11a/07_img.jpg" width="200" height="150" hspace="10"
23:   vspace="10" style="position:absolute;top:474px;left:485px" /></a>
24: </body>
25 </html>

This page is just a simple application of XHTML with image elements. It should be easy to read and understand. Next, we look at a more exciting interactive card game.

11.5.2 An interactive card game

In this section, we show how to use the removeChild() method to construct an interactive card game. This game demonstrates that even a very simple use of the function can create an interesting effect. The rules of the game are simple. Five cards are generated randomly, with one master card and four associated cards below it. The value of the master card is displayed at the top level. The values of the four associated, or guess, cards are covered and located on the right below the master card.

Based on an elimination method, a player needs to guess which one of the associated cards has a smaller value than the master card. The player needs to eliminate any three out of the four unwanted cards by clicking on each one of them in turn. A mouse click on any of the associated cards has the effect of eliminating it from the screen. As you can imagine, the removeChild() function is employed to remove it from the DOM tree. When the final card is clicked, the value of the card is reviewed. If the value of the card is less than the master card, a "You Win" message is displayed at the bottom. For simplicity, no fancy styles or additional features are implemented in this example. Only the bare bones of a gambling game are constructed.

The card game involves 13 cards and they are arranged as follows:



Picture File : 1.jpg  Heart 2
Picture File : 2.jpg  Heart 3
      *** ***  *** ***
Picture File : 12.jpg  Heart K
Picture File : 13.jpg  Heart A

The careful design of the file names provides a handy way to display and to compare values. Some screen shots shown in Figs 11.22 and 11.23 may be useful to help understand the discussion of the game.

Figure 11.22. ex11-11.htm

graphics/11fig22.jpg


Figure 11.23. An interactive card game

graphics/11fig23.jpg


The interface part of the game is listed below:



Example: ex11-11.htm - An Interactive Card Game

 1:  <?xml version="1.0" encoding="iso-8859-1"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5:  <head><title> An Interactive Card Game -- ex1111.htm</title></head>
 6:  <style>
 7:   .butSt{background-color:#dddddd;font-family:arial;font-weight:bold;
 8:      font-size:14pt;color:#880000;width:150px;height:35px}
 9:  </style>
10:  <body style="background:#000088;font-family:arial;font-size:20pt;
11:     color:#ffff00;font-weight:bold;text-align:center">
12:   Card Game:Find The Card Less Than <br />The Host Card<br /><br />
13:  <div id="id01" style="color:#ffffff;font-size:16pt">Delete The Card You
14:    Don't Want <br />By A Mouse Click</div><br/>
15:
16:  <img src="card000.jpg" id="cov00" name="cov00" alt="Pic 0"
17:      width="100" height="130" /><br /><br />
18:  <img src="card000.jpg" id="cId00" name="cId00" alt="Pic 1"
19:      width="100" height="130" onclick="myDelApp(0)" />
20:  <img src="card002.jpg" id="cId01" name="cId01" alt="Pic 2"
21:      width="100" height="130" onclick="myDelApp(1)" />
22:  <img src="card000.jpg" id="cId02" name="cId02" alt="Pic 3"
23:      width="100" height="130" onclick="myDelApp(2)" />
24:  <img src="card002.jpg" id="cId03" name="cId03" alt="Pic 4"
25:      width="100" height="130" onclick="myDelApp(3)" />
26:  <br /><br /><div id="outMsg"></div>
27:
28: <script src="ex1111.js"></script>
29: </body>
30: </html>

This page contains five images. The first one defined in lines 1617 is the master (or host) card and others in lines 1825 are the associated ones. The associated cards have identities arranging from "cId00" to "cId03." If the first associated card is clicked by a mouse, the function myDelApp(0) is called to eliminate this card by removing it from the DOM tree. When the final card is clicked, the value of the card is shown and is compared to the value of the master card. If the value is bigger than the master card, the "You Lose" message is displayed at the bottom. Otherwise the "You Win" message is displayed.

The external program file ex11-11.js is listed as follows:



Example: ex11-11.js - The ECMAScript For ex1111.htm

 1:  function genRan()
 2:  {
 3:   tmpV = Math.round(Math.random()*14)
 4:   while(tmpV <1 || tmpV > 13) tmpV = Math.round(Math.random()*14)
 5:   return tmpV
 6:  }
 7:
 8:  hostcard = 0
 9:  card = new Array()
10:  function getNo()
11:  {
12:    hostcard = genRan()
13:    document.getElementById("cov00").src = hostcard+".jpg"
14:    card[0] = genRan()
15:    while (hostcard == card[0]) card[0] = genRan()
16:    card[1] = genRan()
17:    while ((hostcard == card[1]) ||(card[0] == card[1])) card[1] = genRan()
18:    card[2] = genRan()
19:    while ((hostcard == card[2])||(card[0] == card[2])||
20:           (card[1]==card[2])) card[2] = genRan()
21:    card[3] = genRan()
22:    while ((hostcard == card[3])||(card[0] == card[3])||
23:           (card[1]==card[3])||(card[2]==card[3])) card[3] = genRan()
24:  }
25:  getNo()
26:
27:  function myDelApp(stV)
28:  {
29:   if (document.images.length < 3) {
30:    document.images.item(1).src = card[stV]+".jpg"
31:    if (hostcard > card[stV]) llSt = "You Win"
32:    else llSt = "You Lose"
33:    document.getElementById("outMsg").innerHTML = llSt
34:   } else {
35:    tmpV ="cId0"+stV
36:    objV = document.getElementById(tmpV)
37:    document.body.removeChild(objV)
38:   }
39:
40: }

The first function genRan() in this program is a random number generator and returns an integer between 1 and 13. We first initialize the master card value to 0 in line 8 and define an array to hold the values of all associated cards in line 9.

One thing you need to be careful with when dealing with card games is that no card should appear twice in any circumstances. This is the job of a function called getNo() defined in lines 1024. This function assigns random numbers to the cards and prevents any duplication at the same time. Note that the main focus of this demonstration example is on some basic ideas and techniques when dealing with card games. For clarity and readability, no commercial protection coding or tricks are used.

To prevent card duplication, we first generate a random value for the master card. The next step is to get another random number for the first associated card. The whileloop in line 15 is used to prevent any duplication. The statements in the while-loop can be interpreted as: while the first associated card (card[0]) equals the master card (hostcard), get another random number for card[0]. For every associated card, you need to employ a while-loop to compare all previous cards to avoid any duplication. That is, if duplication has occurred, the card needs to be regenerated. Since you have only four associated cards, the function getNo() is not too complicated to handle. After the execution of this getNo() function, all cards should have a unique value associated with them.

When one of the associated cards is clicked, the myDelApp() function is called. For example, when the second associated card is pressed, the function myDelApp(1) is executed and the statements in lines 3537



tmpV ="cId0"+stV
objV = document.getElementById(tmpV)
document.body.removeChild(objV)

get the identity of the card and ultimately remove it from the DOM tree. When a card (i.e., an image) is deleted from the DOM tree, the document.images.length value will automatically be decreased by 1. You can use this value to detect how many images are on the screen. If this number is less than 3, as indicated in line 29, you know that only two cards, the "master" and the last associated, are left. In this case, the following statements are executed:



document.images.item(1).src = card[stV]+".jpg"
if (hostcard > card[stV]) llSt = "You Win"
else llSt = "You Lose"

Since only two cards are left, the document.images.item(1) object represents the last associated card. The first statement above gets the value of the card and displays it. If the value is less than the master card value (hostcard), the local string is assigned the "You Win" message. Otherwise the "You Lose" message is assigned. This local string llSt is then output to the screen by executing the statement in line 33.

    Table of Contents

    Previous Next