Приглашаем посетить
Горький (gorkiy-lit.ru)

6.4 Basic mouse clicks and position control

Table of Contents

Previous Next

6.4 Basic mouse clicks and position control

6.4.1 My first mouse click page

In XHTML, the first mouse click element is the anchor. Without knowledge of the mouse events, the anchor is a good practical way to implement a mouse click and provides links to the outside world. In fact anchor itself is a click event without a button. Another popular use of mouse clicks is using buttons. Buttons can be defined as an attribute inside the <input> element and associated with forms <form>. Let's consider the following "My First Mouse Click Page."



Example: ex06-12.htm - My First Mouse Click Page

 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>
 6:    <title> My First Mouse Click Page - ex06-12.htm </title>
 7: </head>
 8: <style>
 9:    .text01{font-family:Arial;color:red;font-weight:bold;font-size:14pt}
10: </style>
11: <body>
12: <div class="text01" align="center"><br />My First Mouse Click Page
13: <form><br />
14: <input type="button" value="Button 1" onclick='alert("Button 1")' />&nbsp;
15: <input type="button" value="Button 2" onclick='alert("Button 2")' />&nbsp;
16: <input type="button" value="Button 3" onclick='alert("Button 3")' />&nbsp;
17: <input type="button" value="Button 4" onclick='alert("Button 4")' />&nbsp;
18: <input type="button" value="Button 5" onclick='alert("Button 5")' />&nbsp;
19: </form>
20: </div>
21: </body>
22: </html>

This page is very simple. After the main header in line 12, five buttons, "Button 1," "Button 2," "Button 3," "Button 4," and "Button 5," are defined. These buttons are all inside the form element <form> in lines 1319. The mouse click event for each button is controlled by the onclick event as illustrated in line 14. For example, when a mouse click happens inside "Button 1," an alert window is triggered to display the message "Button 1" (Figs 6.22 and 6.23). The non-break space &nbsp; is used to separate each button. The form element <form> is not compulsory in the latest W3C recommendations. However, without the form declaration, some earlier browsers may not generate the buttons on the screen.

Figure 6.22. ex06-12.htm

graphics/06fig22.gif


Figure 6.23. Onclick Button 1

graphics/06fig23.gif


6.4.2 Buttons with style and a mouse click counter

Outputting the mouse click message to an alert window is useful to track down the click events. In practice, you may also want some more features. One such demand is to record and display the number of mouse clicks on certain areas (including icons and buttons). This number of hits and counting capability are vital techniques for many game designs. Suppose you have two buttons on a page. The following code (a script function) can be used to record and display how many mouse clicks occur in a particular region.



Listing: ex06-11.txt

 1:   <script>
 2:   var hits1 = 0;
 3:   var hits2 = 0;
 4:
 5:  function mouse_click(but_no)
 6:   {
 7:    if (but_no == 1)
 8:    {
 9:      hits1 += 1;
10:     document.getElementById("but01").innerHTML="<h3>"+hits1+"</h3>";
11:   }
12:   if (but_no == 2)
13:   {
14:     hits2 += 1;
15;     document.getElementById("but02").innerHTML="<h3> "+hits2+"</h3>";
16:   }
17:  }
18:  </script>

This code fragment contains one script function inside the <script> element (lines 118). Lines 23 define two variables hits1 and hits2 to record how many times mouse clicks are involved. The function itself (line 5) requires one input argument but_no to indicate which button has been clicked. If the argument but_no equals 1, the record hits1 will be updated by 1. This is illustrated in line 9. In line 10, the output message "<h3>"+hits1+"</h3>" is sent to the field with id="but01". Since <h3> is an element with CSS style, the innerHTML is used to interpret the result. To put this function into action, consider the following example ex06-13.htm:



Example: ex06-13.htm - My Mouse Click And Count

 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>
 6:     <title> My Mouse Click and Count - ex06-13.htm </title>
 7: </head>
 8: <style>
 9:     h3{ font-family:Arial;font-size:20;color:black}
10: </style>
11:
12: <script>
13:  var hits1 = 0;
14:  var hits2 = 0;
15:  function mouse_click(but_no)
16:  {
17:    if (but_no == 1)
18:    {
19:     hits1 += 1;
20:     document.getElementById("but01").innerHTML="<h3>"+hits1+"</h3>";
21:    }
22:    if (but_no == 2)
23:    {
24:     hits2 += 1;
25:     document.getElementById("but02").innerHTML="<h3>"+hits2+"</h3>";
26:    }
27:  }
28: </script>
29: <body>
30:   <div align="center"><h3><br />Mouse Click and Count<br /></h3>
31:   <input type="button"
32:    style='font-family:Arial;background-color:#ffaaaa;
33:      font-weight:bold;font-size:18pt'
34:      onmouseover='this.style.color="red"'
35:      onmouseout='this.style.color="black"'
36:      value="Button 1" onclick='mouse_click(1)' />&nbsp;
37:
38:  <input type="button"
39:   style='font-family:Arial;background-color:#aaffaa;
40:     font-weight:bold;font-size:18pt'
41:     onmouseover='this.style.color="red"'
42:     onmouseout='this.style.color="black"'
43:     value="Button 2" onclick='mouse_click(2)' />&nbsp;<br /><br />
44:
45: <table cellspacing="20">
46:   <tr align="center">
47:    <td id="but01" style="background-color:#ffaaaa;
48:       width:130px;height:70px"><h3>0</h3></td>
49:    <td id="but02" style="background-color:#aaffaa;
50:       width:130px;height:70px"><h3>0</h3></td>
51:   </tr></table>
52: </div>
53: </body>
54: </html>

The script function mouse_click() in ex06-11.txt is put into lines 1228 so that it can be called inside the XHTML page. Lines 3136 define a button ready to call the mouse_click() function. The onmouseover and onmouseout attributes of the button are used to change the button color and to highlight the text. When the button is clicked, the onclick event handler (line 36) activates the script function mouse_click(1) with the input argument 1 to indicate "Button 1" has been clicked. The counting result is sent to the table field in line 47 with an id="but01".

The main feature of this example is the two buttons defined in lines 3143. The button technique is used here to trigger the onmouseover, onmouseout, and onclick events (see Fig. 6.24).

Figure 6.24. ex06-13.htm

graphics/06fig24.gif


If you don't want to use buttons, you can design a new example to allow a mouse click and counting around a region. For example, you can replace the body part of example ex06-13.htm with the following code fragment ex06-12.txt, and call this new example ex06-14.htm.



Listing: ex06-12.txt - Code Fragment For ex06-14.htm

 1: <body>
 2:  <div align="center"><h3><br />Mouse Click and Count<br /></h3>
 3:  <br />
 4:  <table cellspacing="20" border=0>
 5:   <tr align="center">
 6:    <td id="but01"
 7:       style="background-color:#ffaaaa;width:130px;height:150px"
 8:       onclick='mouse_click(1)'><h3>0</h3></td>
 9:    <td id="but02"
10:       style="background-color:#aaffaa;width:130px;height:150px"
11:       onclick='mouse_click(2)'><h3>0</h3></td>
12:     </tr></table>
13:  </div>
14: </body>

As you can see, the onclick event handler (line 8) is inside the <td> element. If a mouse click happens inside this region, the counting will be increased and output the result to the same location. Figure 6.25 shows the screen shot of this example. Since XHTML supports onclick events for almost all elements, you can implement this mouse click and counting technique on various elements and shapes.

Figure 6.25. ex06-14.htm

graphics/06fig25.gif


6.4.3 Mouse positions

Mouse (or cursor) positions provide helpful information as a user interface and play a vital role in any moving object applications. To track down mouse movements, you need to understand something called "Event Model." Unfortunately, the set-up of an event model is a browser-dependent process. That means you need browser detection code. With detection, you can easily develop a mouse movement page with backward compatibility. The following page is a classic one and is popular amongst Web professionals.



Example: ex06-15.htm - My Mouse Positions

 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>
 6:   <title> My Mouse Positions - ex06-15.htm </title>
 7: <script>
 8:   var tempX = 0;
 9:   var tempY = 0;
10:   var IE = document.all?true:false;
11:
12:   if (!IE) document.captureEvents(Event.MOUSEMOVE);
13:   document.onmousemove = getPosition;
14:
15:   function getPosition(e)
16:   {
17:    if (IE)
18:    { // grab the mouse x-y co-ordinates if browser is IE
19:     tempX = event.clientX;
20:     tempY = event.clientY;
21:    }
22:    else
23:    { // grab the mouse x-y co-ordinates if browser is NS
24:     tempX = e.pageX;
25:     tempY = e.pageY;
26:    }
27:
28:    if (tempX < 0){tempX = 0;}
29:    if (tempY < 0){tempY = 0;}
30:    document.mouse_f.MouseX.value = tempX;
31:    document.mouse_f.MouseY.value = tempY;
32:    return true;
33:   }
34:
35: </script>
36: </head>
37: <body>
38: <h2 style="font-family:times;font-size:16pt">My Mouse Position Page</h2>
39:
40: <form id="mouse_f" name="mouse_f">
41:  Mouse Position on X
42:  <input type="text" id="MouseX" name="MouseX" value="0" size="4" /><br />
43:  Mouse Position on Y
44:  <input type="text" id="MouseY" name="MouseY" value="0" size="4" /><br />
45: </form>
46:
47: </body>
48: </html>

First, a simple browser detection code in line 10 is used so that the proper mouse move event can be set in lines 1213. The script function getPosition() captures the mouse position. By setting this getPosition() function in the mouse move event, this function is called whenever the mouse changes its position. Inside this script function, a simple conditional statement is employed to handle the browser differences. If the browser is IE, the x and y mouse coordinates from IE's event model are obtained. If the browser is NS, we get mouse coordinates from events e.pageX and e.pageY respectively. The temporary mouse positions, tempX and tempY, are assigned to the XHTML form element in lines 3031 for display purposes (Fig. 6.26). As a result, this page captures the mouse movement and displays the mouse coordinates on a browser's screen.

Figure 6.26. ex06-15.htm

graphics/06fig26.gif


If you replace lines 30 and 31 by the following code



document.getElementById("MouseX").value = tempX;
document.getElementById("MouseY").value = tempY;

(i.e., use getElementById), you can eliminate the use of the form element. This provides a clearer and a more structured understanding of the process.

With this approach, you can rewrite the body part of this example using the listing in ex06-13.txt and have a new mouse position page with style (ex06-16.htm). This page will only work on W3C standard browsers.



Listing: ex06-13.txt - Code Fragment For ex06-16.htm

 1: <body>
 2:
 3:  <h3>My Mouse Position Page -- ex06-16.htm</h3><br />
 4:  <h4>
 5:  Mouse Position on X
 6:  <input type="text" id="MouseX" name="MouseX" value="0"
 7:         style="font-family:arial;color:Blue;
 8:           font-size:16pt;background:#aaaaee" size="4" /><br />
 9:
10:  Mouse Position on Y
11:  <input type="text" id="MouseY" name="MouseY" value="0"
12:         style="font-family:arial;color:blue;
13:            font-size:16pt;background:#aaeeaa" size="4" /><br />
14:  </h4>
15:  </body>

The screen captures of ex06-15.htm and ex06-16.htm are shown in Figs 6.26 and 6.27.

Figure 6.27. ex06-16.htm

graphics/06fig27.gif


Once you have a technique for tracking down the mouse movement, you can develop Web pages to allow texts and/or images to follow it.

6.4.4 Moving text and images with a mouse

In this section, we consider examples of simple moving objects on Web pages. Since we haven't formally introduced Dynamic XHTML (DXHTML), we will keep the discussion simple. More details on moving objects are given in Chapter 9. The idea of moving objects with a mouse is basically a two-step process.

  • Capture the mouse position when the mouse moves.

  • Assign the new mouse position to an object.

Capturing the mouse position can be done by techniques already discussed in section 6.4.3. In order to change the object position in real time, you need the CSS position properties and DOM interaction. As a demonstration, a simple text message "Cursor Text" is generated. This text will follow your mouse movement anywhere inside the browser screen. Consider the example ex06-17.htm below:



Example: ex06-17.htm - Moving Text With Mouse

 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:
 6: <head>
 7:   <title> Moving Text With Mouse - ex06-17.htm </title>
 8: <script>
 9:   var tempX = 0;
10:   var tempY = 0;
11:   var IE = document.all?true:false;
12:
13:   if (!IE) document.captureEvents(Event.MOUSEMOVE);
14:   document.onmousemove = cursor;
15:
16:  function cursor(e)
17:  {
18:
19:    if (IE)
20:    { // grab the mouse x-y co-ordinates if browser is IE
21:     tempX = event.clientX;
22:     tempY = event.clientY;
23:    }
24:    else
25:    { // grab the mouse x-y co-ordinates if browser is NS
26:     tempX = e.pageX;
27:     tempY = e.pageY;
28:    }
29:    document.getElementById("mov_text").style.visibility="visible";
30:    document.getElementById("mov_text").style.position="absolute";
31:    document.getElementById("mov_text").style.left=tempX+10+"px";
32:    document.getElementById("mov_text").style.top=tempY+"px";
33:  }
34:
35: </script>
36: </head>
37:
38: <style> h3{font-family:arial;font-size:12pt;color:#ff0000}</style>
39: <body>
40:
41: <h3 style="font-size:14pt;color:#0000ff">Moving Text With Mouse</h3>
42:
43: <h3 id="mov_text" style="visibility:hidden">Cursor Text</h3>
44:
45: </body>
46: </html>

This example is a modification of ex06-15.htm. In line 43, the text "Cursor Text" is generated using the element <span> and id="mov_text". The initial CCS visibility setting is hidden so that it is not displayed. The next step is to set up the browser detection code and event model as described in section 6.4.3. The script function cursor() is called once a mouse movement is detected. The new mouse x-y coordinates are assigned to the variables tempX and tempY respectively. In lines 2932, we use the DOM structure to access the CSS properties of this "mov_text" text. Line 29 is used to set the visibility of the text to visible so that the text can be displayed. Line 30 is to set the coordinate system as absolute. Line 31 assigns the new text's "left" position as the x coordinate of the mouse plus 10 pixels. Line 32 sets the mouse's y coordinate to the "top" position of the text. The script function cursor() is activated whenever there is a mouse movement. You now have a truly real-time Web page with a moving object (see Fig. 6.28).

Figure 6.28. ex06-17.htm

graphics/06fig28.gif


If you use the XHTML image element <img> instead of the text, you will have a moving image along with the mouse. The first thing you need to do is to replace the body part of example ex06-17.htm (lines 3945) with the listing in ex06-14.txt and call this example ex06-18.htm.



Listing: ex06-14.txt - Code Fragment For ex06-18.htm

1:  <body>
2:  <h3>Image With Mouse Movement</h3>
3:  <img id="mov_object" style="visibility:hidden" src="logo_web.jpg"
4:     width="100" height="60" />
5:  </body>

This code fragment defines an image object with id="mov_object". Next, you replace all texts "mov_text" by this new identity "mov_object." The script function cursor() makes the image move along with the mouse (see Fig. 6.29).

Figure 6.29. ex06-18.htm

graphics/06fig29.gif


    Table of Contents

    Previous Next