Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 15 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
15
Dung lượng
373,27 KB
Nội dung
var isArrowLeft=true; function ChangeMe(target) { isArrowLeft=!isArrowLeft; if(isArrowLeft) target.src = “images/ArrowLeft.gif”; else target.src = “images/ArrowRight.gif”; } After rendering the page, the isArrowLeft variable is initially set to true. And when the image is clicked, the ChangeMe() function is called with the image object being passed in. Within that function the image object is called as target. The isArrowLeft variable, which holds a boolean value, is set to its opposite with the first statement. Then that target image’s src attribute is set based on what the isArrowLeft value holds. A similar example to this is found at the start of Chapter 7, but it goes further to include more intricate string manipulation with the split() function and referencing an array member. It also uses the prototype keyword to add a method called substitute() to all strings. This more in-depth example will make better sense after you digest the next chapter, which has information about objects and more about functions. Programmatically Populating the Options in <select> When a choice is made in one drop-down list, it is often handy to populate a second drop-down list with appropriate choices. With Ajax, this is fairly straightforward, and this sample will show you how to implement the JavaScript side of things, dynamically adding new <option> objects to the contents of a drop-down list. The <select> element is what builds a drop-down list (or a list box if the size attribute has been set). This next Try It Out has you build a drop-down list by using <select>, and then add a textbox and button underneath. When you type some text and click the button, it will build a new option in the drop-down list. 21 Introduction to DHTML Finding Objects with document.getElementById() Before you go further, you need to know about an important tool at your disposal. In the last section, you worked with an image object by using the special this keyword avail- able inside an event handler. It was convenient, but what if you wanted to find an existing object on the page and change its properties? This is where, historically, different browsers have had different approaches to get the job done. For example, Internet Explorer (IE) would use document.all, and Netscape would use document.layers. Fortunately, a common method on the document object now enables you to search through a web page and find any object by its ID anywhere on the page: getElementById(). To effectively use this, the elements being referenced must have id attributes applied. In the remain- ing samples in the chapter and in even more detail in the next chapter, you’ll see the use of document.getElementById(). 05_78544X ch02.qxp 7/18/06 3:12 PM Page 21 Try It Out Dynamic Drop-Down Options Begin with the following HTML: <select id=”mySelect”></select><br /> <input type=”text” id=”newOption” /> <input type=”button” value=”Add a new option to the drop-down” onclick=”addOption(document.getElementById(‘newOption’).value);” /> The onclick event handler for the button calls a function named addOption, using the getElementById() method in order to find the text value in the textbox named newOption. Next, here is the addOption function that you should add: <script type=”text/javascript”> function addOption(optionText) { var objSelect=document.getElementById(“mySelect”); objSelect[objSelect.length] = new Option(optionText); } </script> This function is a little different from the last one you saw: It accepts a parameter called optionText, called out in the parentheses after the name of the function. When called, this function expects a string value will be passed in for optionText. This is used later in the function to specify the text that should be associated with the new Option object being built. A reference is obtained with document.getElementById() to the <select> element called mySelect. This reference, named objSelect, is used to update the contents of the options. The square brackets indicate that an array is being referenced, and in this case it’s an array of options under the <select> element . The value inside the square brackets defines an index to which piece of the array is being modified. The new Option object is placed in as the very last piece of the array by having the index refer to the current length of the array. When this is added, the new option is immediately visible in the drop- down list, as shown in Figure 2-6. Notice how, in the top screen of Figure 2-6, the select box is empty. When you add the phrase “Who says HTML is boring” and click the “Add a new option to the drop- down” button, the bottom of Figure 2-6 shows the finished result. If this <select> element were in an HTML form and was submitted to the server, the value posted back would be exactly the same as whatever text the user had typed. If you want to have a different value posted back to the server, then you can specify two parameters when building out the new Option object, the first being the text to show the user and the second being the value that gets posted back to the server. To illustrate the importance of this concept, consider a drop-down list of states. You would want to display the state name to the user, but once it was posted back to the server, you would want your application to know about the state code. This is important because you are now associating what is important to the user, a friendly state name, with what is important to the computer, the unique state code. 22 Chapter 2 05_78544X ch02.qxp 7/18/06 3:12 PM Page 22 Using the innerHTML Property A very handy feature of <span> and <div> elements that first showed up in IE4 is the innerHTML prop- erty. This represents what the browser considers to be the actual HTML it will use to present the contents of the <div> or <span>. Although the innerHTML property is not officially a part of the World Wide Web Consortium (W3C) standard, it is still very useful, especially for Ajax — useful enough that it was also adopted by Netscape starting in version 6 of their browser. Figure 2-6 Try It Out Using the innerHTML Property To get a quick idea of what it can do, you can put a <span> on your page with <textarea> and <input type=”checkbox”> elements inside, and after the <span>, a button to present a pop-up showing what the browser sees inside the innerHTML of the <span>. Here’s the code: <span id=”spanTxt”> <textarea></textarea> <input type=”checkbox” /> </span> <input type=”button” value=”Show the innerHTML” onclick=”alert(document.getElementById(‘spanTxt’).innerHTML);” /> 23 Introduction to DHTML 05_78544X ch02.qxp 7/18/06 3:12 PM Page 23 When you examine the contents of innerHTML, you’ll find that things differ between different browsers. With the page loaded in Internet Explorer, try typing something in the <textarea>, and you’ll find that when you click the button, the pop-up alert() shows exactly the HTML that would re-create the <span> in its current state. Click the checkbox as well, and then click the button to bring up the alert() again, and note that the CHECKED attribute then appears. See Figure 2-7 for a sample of what is shown. Unfortunately, in other browsers this nice dynamic reference to innerHTML doesn’t hap- pen; they simply show the page’s source for what’s inside the <span>. Figure 2-7 However, something that is possible with both Netscape and Firefox and IE is that you can change the innerHTML contents programmatically. Consider for a moment the potential. A <div> or <span> can be set up on a page, and with that page still showing, the browser can send an asynchronous request to the server, receive raw HTML data back, and conveniently place the result in the innerHTML property. That’s the very basis of Ajax, dynamically updating only specific content on a page without having to refresh the whole thing. Another way to place new content on a page dynamically is by using createElement() and its rela- tives, which are discussed in the next chapter. Manipulating the Style Sheet A primary feature of writing DHTML code is being able to dynamically change the style sheet. Using JavaScript you have the ability to manipulate the style sheet in a number of different ways. One of the ways to make these dynamic changes is to respond to user interaction on the page by hooking into ele- ment events. An example of one of these events is the onclick event of the anchor element. Before making any changes to the style sheet, JavaScript must know what element on the page you want to affect. The most common way to find the element you are looking for on the page is to use the function document.getElementById(). A very useful attribute of the style sheet is the display attribute. The display attribute will determine how an element is displayed on the page. When the element is set to display:block the element will take up space on the page. When the element is set to display:none the element is removed from the elements displayed on the page. 24 Chapter 2 05_78544X ch02.qxp 7/18/06 3:12 PM Page 24 To illustrate this behavior, the next Try It Out demonstrates how to build a panel for which you can tog- gle the display attributes. The result for the user is that it appears as if you are hiding the panel with one click and showing the panel with the next click. Try It Out Showing and Hiding a DHTML Panel For this example, begin by adding the following HTML to your page: <a href=”javascript:void(0);” onclick=”ShowHide(‘divDetails’);UpdateText(this);”> Show Details </a> <div id=”divDetails” style=”display:none;”> Details Panel </div> This block has two sections. The first part of the HTML renders a link on the page that allows the user to click on an element to initiate the change to the style sheet. The next part of the code is the panel that is affected by the change. This is the panel that is hidden from and then displayed again to the user. Next, add the following JavaScript to the page: <script type=”text/javascript”> function ShowHide(elementId) { var element = document.getElementById(elementId); if(element.style.display != “block”) { element.style.display = “block”; } else { element.style.display = “none”; } } function UpdateText(element) { if(element.innerHTML.indexOf(“Show”) != -1) { element.innerHTML = “Hide Details”; } else { element.innerHTML = “Show Details”; } } </script> 25 Introduction to DHTML 05_78544X ch02.qxp 7/18/06 3:12 PM Page 25 The preceding JavaScript changes the web page in two ways. The ShowHide function does the work of finding the panel on the page, and then updating the style sheet’s display property. If the element is not being shown to the user ( display:block), then the settings are updated to display the panel. Alternatively, if the panel is being displayed, then the style sheet is updated to hide the panel. The next function UpdateText uses the innerHTML property you learned about in the last section, to update the text in the link the user is clicking on. Notice in the HTML that when the function is called, a single argument of this is passed into the function. This element reference allows the function to know which element initiated the call to the function. With this reference, the function examines the innerHTML of the link and makes the appropriate changes to the text displayed to the user. Creating a Context Menu The last Try It Out in this chapter is for IE only and shows how to reference the various style properties on a <div> in order to make it visible or hidden and reposition it on the screen. You will use this <div> as a custom context menu that appears on the page when the right mouse button on a right-handed mouse is clicked (or whatever alternate mouse button is configured). The event that fires when this click is done is oncontextmenu. You will handle this event, first just showing the x and y position of the mouse in the sta- tus window and deferring the normal behavior of an alternate click: showing the browser’s context menu. Try It Out Adding a Context Menu If you’ve been working through all of the samples, then there is already an event handler in place on the <body> tag to handle onload. You’ll keep that intact and add another event handler for oncontextmenu like this: <body onload=”window.status=’It\’s a beautiful day’;” oncontextmenu=”contextMenuClick(); return false;”> And as you may have guessed, the return false; statement bypasses the normal behavior of this event handler, which would bring up the browser’s context menu. So, you can now add a function in the <script> tag called contextMenuClick(), which simply examines a couple of properties called clientX and clientY found on the event object: function contextMenuClick() { window.status=event.clientX+’ ‘+event.clientY; } When you test this, you’ll find that the event.clientX and event.clientY properties give the x and y coordinates of the exact location of the mouse during the click. So, when you render the page and right- click somewhere, the status menu shows those x and y coordinates. You can put that information to work by using the coordinates to place a <div>. Add this code anywhere in the body: <div id=”contextMenu” style=”position:absolute; z-index:999; visibility:hidden; border:3px solid #000080; background-color:#4000C0; color:#FFFF00”> My excellent context menu </div> 26 Chapter 2 05_78544X ch02.qxp 7/18/06 3:12 PM Page 26 Now that you have this <div>, you can place it using its style.left and style.top properties. You also need to make it visible. Update the existing contextMenuClick() function with this code: function contextMenuClick() { var objContextMenu=document.getElementById(“contextMenu”); objContextMenu.style.left=event.clientX; objContextMenu.style.top=event.clientY; objContextMenu.style.visibility=”visible”; } In this case, you use that special method of the document object mentioned earlier in the chapter, getElementById(), to find the contextMenu object by its id and put that reference in a new variable called objContextMenu. This effectively gives you a handy pointer to the <div>, which you then use with the next three statements to update the position and visibility of the <div>. With that, wherever you right-click on the page the context menu is shown. Summary This chapter was designed to be an easy walkthrough to introduce you to some of the important con- cepts around DHTML, with most coverage given to JavaScript. At this point, you can take the principles you’ve learned and continue to experiment! In this chapter, you looked at the following: ❑ Some quick coverage of JavaScript syntax and some examples of presenting data ❑ Retrieving data from the user ❑ Handling events with JavaScript functions ❑ Direct manipulation of HTML objects These concepts will be essential as you learn more about Ajax. From here, you can dig deeper into how JavaScript objects work in the next chapter. 27 Introduction to DHTML 05_78544X ch02.qxp 7/18/06 3:12 PM Page 27 05_78544X ch02.qxp 7/18/06 3:12 PM Page 28 3 JavaScript and the Document Object Model Hypertext Markup Language (HTML) is currently the language of the Internet. All browsers know how to parse and render HTML into a format that is easily viewed and understood by humans. When a browser is instructed to retrieve a page from a server, what is returned to the browser is a document that contains HTML. The browser can then interpret and render this HTML document for presentation to the user. HTML documents are static representations of a user interface. Once this interface is presented to the user, the interface is typically unable to change without being re-sent to the server for process- ing, and another HTML document is returned to and rendered for the user. JavaScript and the Document Object Model (DOM) provide a way that you can change this rendered display pro- grammatically and dynamically, according to events such as a user clicking the mouse, all from within the browser. In this chapter, you take a look at: ❑ The development of JavaScript ❑ The basics of the language ❑ Advanced JavaScript features ❑ The HTML Document Object Model and associated standards ❑ Using JavaScript to programmatically and dynamically change rendered HTML docu- ments with the Document Object Model All the code samples for this chapter are available for downloading at http://beginningajax .com . Just visit the site and download the samples for Chapter 3. They are provided as a Visual Studio .NET 2005 web site project. Simply load and execute each page as required. 06_78544X ch03.qxp 7/18/06 3:12 PM Page 29 From Static to Dynamic — A Brief History Approximately 10 years ago in 1995, almost a lifetime in computer industry terms, a man by the name of Brendan Eich developed a loosely typed scripting language intended to make Netscape Navigator’s newly added Java support more accessible to non-Java programmers. On December 4, 1995, Netscape and Sun jointly announced the existence of the new JavaScript language to the world. Although the original intent of JavaScript was to further the Java language, it soon took on a life of its own. JavaScript was commonly used to manipulate images and HTML documents’ contents, instead of just manipulating and controlling Java applets. Although JavaScript retains the use of Java within its name, currently it bears no relationship to the core Java language other than the fact that Java was used to model the original language characteristics of JavaScript. This is often a source of confusion for devel- opers, who assume JavaScript to be a subset of the Java core language. The development of JavaScript has taken on a life of its own. Using JavaScript, previously static web content could now be dynamically manipulated. Web program- mers the world over began to see enormous new potential in their web applications. Initially, a vast majority of web applications used JavaScript simply to change images in response to a mouse click by the user. JavaScript was not without its issues however. Browser compatibility issues and security issues plagued initial implementations, and it has undergone many revisions over the course of its lifetime. JavaScript has evolved into the primary way to control and extend the way in which document authors and web application designers can manipulate the client’s browser experience. Currently, JavaScript is the only way to achieve any sort of dynamic behavior on the client in a cross- browser-compatible way. Microsoft also attempted to address the issue of dynamic content and interaction on web pages by releasing VBScript, a scripting language closely resembling the Visual Basic syntax that was initially limited to the windows platform. Microsoft also released a port of JavaScript, called JScript in 1996. This fragmentation of scripting languages, the fact that Microsoft’s scripting languages were not quite as powerful as JavaScript, and the fact that they were a revision or two behind led to JavaScript being the more popular choice for dynamic web content, in particular, the very popular image swapping effects. Attempts at Standardization As browsers evolved and dynamic web pages became more popular, differences in browsers and their implementations became apparent. Internet Explorer would implement a feature in one way, whereas Netscape would implement features in another (albeit often quite similar) way. The natural effect of this was to attempt to standardize the JavaScript language by submitting it to the European Computer Manufacturers Association (ECMA). JavaScript now had a new name: ECMAScript. ECMAScript was adopted in June 1997 by ECMA, and in 1998 by ISO (International Organization for Standardization). While JavaScript was being standardized, browser vendors were releasing yet another version of their browsers. This was approximately around the time of the 4.0 release generation of browsers. With new abilities to dynamically update client-side content, browser vendors implemented object models within the browser to represent the documents they contained; each of these was known as the Document Object Model (DOM) by their respective browser vendor. Unfortunately, most vendors implemented different object models, making dynamic content difficult on browsers from different vendors. 30 Chapter 3 06_78544X ch03.qxp 7/18/06 3:12 PM Page 30 [...]... necessary, and despite the fact that many browsers will work fine without adhering to these standards, the recommended approach is to adhere to these standards for any current and future web development You will notice in the previous example, that we specified a language attribute with a value of "javascript" instead of a type attribute with a value of "text/javascript" The script still works fine; however,... type attribute with the specified MIME type to be contained within the tag There are some processing differences between the use of the language and type attributes; however, current standards dictate the use of the type attribute, and that’s what will be used throughout this book XHTML is the most recent version of HTML and describes or reformulates HTML elements more inline with XML semantics... code as if it were declared directly within the page It is possible for a browser to have JavaScript disabled, and thus no script will be run when the page is loaded On some browsers, when JavaScript is disabled, the script itself will be rendered to the page as it is written within the HTML page To circumvent this side effect, developers often surround their script with comment tags that cause the script... terminated with a semicolon (;) Again, as noted in Chapter 2, this is not strictly necessary Each line can also be terminated with simply a carriage return function TestFunction() { document.writeln(“I have been written by some javascript”) document.writeln(“This is some more text”) document.writeln(“and yet some more”) } However, to place more than one statement on a line, the statements must be separated with. .. look like: alert( ConstructMessage(“Test Message”) ); More than one argument can be specified for a function’s input parameters by separating the arguments with a comma (,), for example: function MethodWithParameters(arg1, arg2, arg3) { // Do something with the values of arg1, arg2 and arg3 } A function’s arguments can be any primitive type or any type of object Event Handlers You don’t always want script... many browsers, but they were only moderately successful During this time, Microsoft, Netscape, and a number of other companies worked with the World Wide Web Consortium (W3C) to provide a consistent and standardized DOM This was an attempt to remove the current complexity with developing DHTML applications across a variety of browsers The W3C develops interoperable technologies (specifications, guidelines,... visit their web site for more information at www.w3.org Throughout this chapter, you will look at the core components of JavaScript and methods of interacting with and manipulating the DOM While still not fully realized, cross-browser compatibility with respect to the DOM is much improved and is much easier than it previously was However, inconsistencies among vendor implementations still remain, and there... environment of ASP.NET with JavaScript support Technologies such as asynchronous client scripting and Atlas will also be discussed in later chapters of this book All of these advanced technologies make use of the core components and features of JavaScript Digging into Some More JavaScript Basics Chapter 2 started your introduction to JavaScript, particularly in showing how it can interact with the browser... alert(“Hi, I am some simple JavaScript”); Simple Javascript Page 31 Chapter 3 Within the section of the HTML document, you have a tag that contains some basic JavaScript In this case, a simple alert box is displayed with the text “Hi, I am some simple JavaScript.” tags are the primary way of including scripted content in your HTML... line with a semicolon regardless of whether there are multiple statements per line or not This is the recommended approach for all JavaScript development Functions also require that the code block that comprises the function, or body of the function, be encased in curly braces ({ }) The opening and ending curly brace define the start and end of the code block, respectively Code blocks defined within . called with the image object being passed in. Within that function the image object is called as target. The isArrowLeft variable, which holds a boolean value, is set to its opposite with the. made in one drop-down list, it is often handy to populate a second drop-down list with appropriate choices. With Ajax, this is fairly straightforward, and this sample will show you how to implement. dynamically change rendered HTML docu- ments with the Document Object Model All the code samples for this chapter are available for downloading at http://beginningajax .com . Just visit the site and