Beginning JavaScript with DOM Scripting and Ajax 2nd Edition

The goal of this book is to help you understand JavaScipt. If you haven’t looked at JavaScript in a while, you’ll be glad to know a lot has changed for the better. You can use this book as a guide to update your skills. If you are new to JavaScript, this book helps you from the beginning. We start with explaining what a variable is and later move on to how to add Google Maps to your site. This book is full of examples you can use to enhance your site and add features based on the enhanced capabilities built into current browsers.


Russ Ferguson, Christian Heilmann


377 Pages

32731 Reads

89 Downloads

English

PDF Format

8.41 MB

Java Script

Download PDF format


  • Russ Ferguson, Christian Heilmann   
  • 377 Pages   
  • 17 Feb 2016
  • Page - 1

    read more..

  • Page - 2

    For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. Download from Wow! eBook <www.wowebook.com> read more..

  • Page - 3

    v Contents at a Glance About the Authors ��������������������������������������������������������������������������������������������������������������� xv About the Technical Reviewer read more..

  • Page - 4

    xxi Introduction JavaScript has gone though a huge transformation, from being something that was nice to know to being essential to developing web sites that are fully featured and take full advantage of the new capabilities built into browsers. The amount of attention given to JavaScript though libraries and frameworks has grown at an accelerated read more..

  • Page - 5

    1 Chapter 1 Getting Started with JavaScript This book will teach you about JavaScript and how to use it in a practical manner. After you read it, you’ll be able to Understand JavaScript syntax and structures. • Create scripts that are easy to understand and maintain. • Write scripts that do not interfere with others. • Write scripts that make web sites easier to use read more..

  • Page - 6

    Chapter 1 ■ GettinG Started with JavaSCript 2 Other visitors might be dependent on hearing our sites rather than seeing them (via screen readers) and might not be notified of changes achieved via JavaScript. Last but not least, there are users who just cannot have JavaScript enabled—for example, in high-security environments like banks. Therefore, you need to back up a read more..

  • Page - 7

    Chapter 1 ■ GettinG Started with JavaSCript 3 The problem with that is it means every time there is a change, the entire process must be repeated (and the page reloaded). This is cumbersome and slow. It is true that at least the Western world has the benefit of fast Internet connections these days, but displaying a page still means a reload, which could be a read more..

  • Page - 8

    Chapter 1 ■ GettinG Started with JavaSCript 4 The term user agent and the lack of understanding of what a user agent is can also be a problem. Normally, the user agent is a browser like Microsoft Internet Explorer (IE), Chrome, Firefox (Fx), Opera, or Safari. However, browsers are not the only user agents on the Web. Others include Assistive technology that read more..

  • Page - 9

    Chapter 1 ■ GettinG Started with JavaSCript 5 • Increased usability by allowing visitors to change and interact with the user interface without reloading the page For example, by collapsing and expanding sections of the page or offering extra options for visitors with JavaScript. A classic example of this is selection boxes that allow immediate filtering, such as only read more..

  • Page - 10

    Chapter 1 ■ GettinG Started with JavaSCript 6 Note ■ there is also an “opposite” to the script tag—noscript—which allo ws you to add content that will be displayed only when JavaScript is not available. however, noscript is deprecated in XhtML and strict htML, and there is no need for it—if you create JavaScript that is unobtrusive. JavaScript Syntax read more..

  • Page - 11

    Chapter 1 ■ GettinG Started with JavaSCript 7 // If the name the user enters is Chris Heilmann if (myName == "Chris Heilmann") { // then a new window pops up saying hello alert("Hello Me"); } // If the name entered isn't Chris Heilmann else { // say hello to someone else read more..

  • Page - 12

    Chapter 1 ■ GettinG Started with JavaSCript 8 alert( 'Third script Block' ); function doSomething() { alert( 'Function in Third script Block' ); } </script> </body> </html> If you try it out, you’ll see that the alert() dialog in the first script block appears and displays the message First script Block That’s followed by the next read more..

  • Page - 13

    Chapter 1 ■ GettinG Started with JavaSCript 9 call the function, as you might expect, until the script has created it. You can call it in this script by adding it to the third script block like this: <script type="text/javascript"> alert( 'Third script Block '); function doSomething(){ alert( 'Function in Third script Block '); } // Call the function read more..

  • Page - 14

    Chapter 1 ■ GettinG Started with JavaSCript 10 you’d find that the server hosting JavaScript exposes a very different set of host objects, because their functionality is related to things you want to do on a web server. You’ll also see in Chapter 3 that you can use JavaScript to create your own objects. This is a powerful feature that allows you to model read more..

  • Page - 15

    Chapter 1 ■ GettinG Started with JavaSCript 11 if( screen.availWidth < 650 ) { // define the style Variable as the low-resolution style cssName = 'lowres.css'; resolutionInfo = 'low resolution'; // Or if the width of the screen is less than 1000 pixels } else { if( read more..

  • Page - 16

    Chapter 1 ■ GettinG Started with JavaSCript 12 Note that you’re measuring the screen size here, and the user might have a 800×600 s creen, but that doesn’t mean his browser window is maximized. You might be applying a style that is not appropriate. You’re using another object, the document object, to write to the page (an HTML document). The document object’s read more..

  • Page - 17

    13 Chapter 2 Data and Decisions Data and decision making are fundamental to every intelligent program. We’ll begin this chapter by looking at how JavaScript understands, or represents, data. This is important because JavaScript works with a number of data types and manipulates data according to its data type. You can generate unexpected results read more..

  • Page - 18

    ChapTer 2 ■ DaTa anD DeCisions 14 These are sometimes referred to as primitive data types, because they store only single values. There are two slightly different primitive data types as well. These don’t store information, but instead warn you about a particular situation: • Null: Indicates that even though a variable has been created, its current value is null or read more..

  • Page - 19

    ChapTer 2 ■ DaTa anD DeCisions 15 Note ■ Javascript syntax, like english syntax, is a set of rules that makes the language intelligible. Just as a syntax error in english can render a sentence meaningless, a syntax error in Javascript can render the instruction meaningless. You can avoid creating JavaScript syntax errors like the following one by using single read more..

  • Page - 20

    ChapTer 2 ■ DaTa anD DeCisions 16 The escape sequence tells the JavaScript interpreter that the single quotation mark belongs to the string itself and isn’t a delimiter. ASCII is a character-encoding method that uses values from 0 to 254. As an alternative, you can specify characters using the ASCII value in hexadecimal with the \xNN escape sequence. The letter C is read more..

  • Page - 21

    ChapTer 2 ■ DaTa anD DeCisions 17 document.write( 1 + 2 * 3 ); document.write("<br>" ); document.write( 98 % 10 ); </script> </body> </html> You should get this output: 0 2 4 6 7 8 JavaScript, just like math, gives some operators precedence. Multiplication takes a higher precedence than addition, so the read more..

  • Page - 22

    ChapTer 2 ■ DaTa anD DeCisions 18 As you’ve seen, JavaScript’s addition operator adds the values. What it actually does with the two values depends on the data type you’re using. For example, if you’re working with two numbers that have been stored as the number data type, the + operator will add them together. However, if one of the data types you’re read more..

  • Page - 23

    ChapTer 2 ■ DaTa anD DeCisions 19 Note ■ although it is not technically necessary, variable declarations should begin with the keyword var. not using it could have implications, which you will see as you progress. With all that said, let’s start declaring variables. You can declare a variable without initializing it (giving it a value): var myVariable; Then read more..

  • Page - 24

    ChapTer 2 ■ DaTa anD DeCisions 20 Without variables, the only way to do it is to ask users to enter the amount of euros they want to convert twice, and that really isn’t user friendly. Using variables, though, you can store the data temporarily and then call it up as many times as you need to: <html> <body> <script type="text/javascript"> read more..

  • Page - 25

    ChapTer 2 ■ DaTa anD DeCisions 21 var myCalc = 1 + userEnteredNumber; var myResponse = "The number you entered + 1 = " + myCalc; document.write( myResponse ); </script> </body> </html> If you enter 2 at the prompt, you’ll be told that The number you entered + 1 = 12 Rather than adding the two numbers, the read more..

  • Page - 26

    ChapTer 2 ■ DaTa anD DeCisions 22 Let’s see how these functions work in practice: <html> <body> <script type="text/javascript"> var userEnteredNumber = prompt( "Please enter a number", "" ); document.write( typeof( userEnteredNumber ) ); document.write( "<br>" ); document.write( parseFloat( read more..

  • Page - 27

    ChapTer 2 ■ DaTa anD DeCisions 23 If you try entering abc, you’ll just get string NaN NaN NaN number None of the functions can find a valid number, and so they all return NaN, which you can see is a number data type, but not a valid number. This is a good way of checking user input for validity, and you’ll use it to do exactly that later on. So let’s read more..

  • Page - 28

    ChapTer 2 ■ DaTa anD DeCisions 24 Objects JavaScript Supplies You with: String, Date, and Math This is not a complete list of built-in objects, but you will start to get a feel for how objects work by looking at the following ones: • String object: Stores a string, and provides properties and methods for working with strings • Date object: Stores a date, and read more..

  • Page - 29

    ChapTer 2 ■ DaTa anD DeCisions 25 This is what you should see in the browser window: string 3 String So myStringPrimitive is still holding a string primitive after the temporary conversion. You can also create String objects explicitly, using the new keyword together with the String() constructor: <html> <body> <script type="text/javascript"> read more..

  • Page - 30

    ChapTer 2 ■ DaTa anD DeCisions 26 Let’s do that next, using the prompt()method to obtain the user’s e-mail address and then check the input for the @ symbol, returning the index of the symbol using indexOf(): <html> <body> <script type="text/javascript"> var userEmail= prompt("Please enter your emailaddress ", "" ); read more..

  • Page - 31

    ChapTer 2 ■ DaTa anD DeCisions 27 The Date Object JavaScript doesn’t have a primitive date data type, so you can create Date objects only explicitly. You create new Date objects the same way as you create String objects, using the new keyword together with the Date() constructor. This line creates a Date object containing the current date and time: var read more..

  • Page - 32

    ChapTer 2 ■ DaTa anD DeCisions 28 Let’s look at an example that demonstrates some of the methods: <html> <body> <script type="text/javascript"> // Create a new date object var someDate = new Date( "31 Jan 2013 11:59" ); // Retrieve the first four values using the // appropriate get methods read more..

  • Page - 33

    ChapTer 2 ■ DaTa anD DeCisions 29 var originalDate = new Date( originalDate ); // Ask the user to enter the number of days to be // added, and convert to number var addDays = Number( prompt( "Enter number of daysto be added", "1" ) ) // Set a new value for originalDate of originalDate read more..

  • Page - 34

    ChapTer 2 ■ DaTa anD DeCisions 30 You call the methods of the Math object using the following format: Math.methodOfMathObject( aNumber ): alert( "The value of pi is " + Math.PI ); We’ll look at a few of the commonly used methods next. (You can find a complete reference by running a search at https://developer.mozilla.org/en-US/docs/Web_Development.) We’ll look at the read more..

  • Page - 35

    ChapTer 2 ■ DaTa anD DeCisions 31 Generating a Random Number You can generate a fractional random number that is 0 or greater but smaller than 1 using the Math object’s random() method. Usually, you’ll need to multiply the number, and then use one of the rounding methods to make it useful. For example, to mimic a die throw, you’d need to generate a read more..

  • Page - 36

    ChapTer 2 ■ DaTa anD DeCisions 32 Once you’ve populated an array, you can access its elements through their indexes or positions (which, once again, are zero-based) using square brackets: <html> <body> <script type="text/javascript"> var preInitArray = new Array( "First Item" "Second Item", "Third Item" ); read more..

  • Page - 37

    ChapTer 2 ■ DaTa anD DeCisions 33 Let’s put what we’ve discussed about arrays and the Math object into an example. We’ll write a script that randomly selects a banner to display at the top of the page. We’ll use an Array object to hold some image source names, like this: var bannerImages = new Array(); bannerImages[0] = "Banner1.jpg"; bannerImages[1] = read more..

  • Page - 38

    ChapTer 2 ■ DaTa anD DeCisions 34 The Array object provides a number of methods for manipulating arrays, including methods for cutting a number of items from an array or joining two arrays together. We’ll look at the methods for concatenating, slicing, and sorting next. Cutting a Slice of an Array The slice() method is to an Array object what the substring() read more..

  • Page - 39

    ChapTer 2 ■ DaTa anD DeCisions 35 var arrayOne = new Array( "One", "Two", "Three","Four", "Five" ); var arrayTwo = new Array( "ABC", "DEF", "GHI" ); var arrayThree = new Array( "John", "Paul", "George","Ringo" ); var joinedArray = arrayOne.concat( read more..

  • Page - 40

    ChapTer 2 ■ DaTa anD DeCisions 36 document.write(arrayToSort[3] + "<br>" ); document.write(arrayToSort[4] + "<br>" ); </script> </body> </html> The items are arranged like this: Apple Banana Cabbage Lemon Pear If, however, you lower the case of one of the letters—the A of Apple, for example—then you’ll end up with read more..

  • Page - 41

    ChapTer 2 ■ DaTa anD DeCisions 37 The Logical and Comparison Operators There are two main groups of operators we’ll look at: • Data comparison operators: Compare operands and return Boolean values • Logical operators: Test for more than one condition We’ll start with the comparison operators. Comparing Data Table 2-3 lists some of the more commonly used comparison read more..

  • Page - 42

    ChapTer 2 ■ DaTa anD DeCisions 38 document.write("<br>" ); document.write("apple"<"Banana" ) </script> </body> </html> This is what you should get back: true true false When evaluating an expression comparing strings, the JavaScript interpreter compares the ASCII codes for each character in turn of both strings—the first read more..

  • Page - 43

    ChapTer 2 ■ DaTa anD DeCisions 39 If you do need to compare the strings held by two objects, you can use the valueOf() method to perform a comparison of the data values: <html> <body> <script type="text/javascript"> var string1 = new String( "Apple" ); var string2 = new String( "Apple" ); read more..

  • Page - 44

    ChapTer 2 ■ DaTa anD DeCisions 40 If the condition being tested is true, the code within the curly braces following the if will be executed, but won’t if it isn’t. You can also create a block of code to execute should the condition set out in the if not be met, by using a final else statement. Let’s improve on the currency exchange converter you read more..

  • Page - 45

    ChapTer 2 ■ DaTa anD DeCisions 41 if ( userNumber > 10 || userNumber < 1 ) { document.write( "The number you entered is notbetween 1 and 10" ); // Otherwise the number is between 1 and 10, so // write to the page } else { document.write( "The read more..

  • Page - 46

    ChapTer 2 ■ DaTa anD DeCisions 42 You can also use else if statements, where the else statement starts with another if statement, like this: <html> <body> <script type="text/javascript"> var userNumber = Number( prompt( "Enter a number between1 and 10", "" ) ); if ( isNaN( userNumber ) ){ read more..

  • Page - 47

    ChapTer 2 ■ DaTa anD DeCisions 43 JavaScript evaluates switch(expression) and then compares it to each case. As soon as a match is found, the code starts executing at that point and continues through all the case statements until a break is found. It’s often useful to include a default case that will execute if none of the case statements match. This is a read more..

  • Page - 48

    ChapTer 2 ■ DaTa anD DeCisions 44 Repeating Things: Loops In this section, we look at how you can repeat a block of code for as long as a set condition is true. For example, you might want to loop through each input element on an HTML form or through each item in an array. Repeating a Set Number of Times: The for Loop The for loop is designed to read more..

  • Page - 49

    ChapTer 2 ■ DaTa anD DeCisions 45 Earlier, when I discussed arrays, I stated that the Array object has a property that knows the length (how many elements). When looping through arrays, such as in the previous example, you use the name of the array followed by a dot and length as the condition. This prevents the loop from counting beyond the length of the read more..

  • Page - 50

    ChapTer 2 ■ DaTa anD DeCisions 46 In its simplest form, a while loop looks like this: while ( some condition true ) { // Loop code } The condition inside the curly braces can be anything you might use in an if statement. You could use some code like this to allow users to enter numbers and stop the entering process by typing the number 99. read more..

  • Page - 51

    ChapTer 2 ■ DaTa anD DeCisions 47 var arrayIndex = 0; do { userInput = prompt( "Enter a number, or 99 to exit", "99" ); userNumbers[arrayIndex] = userInput; arrayIndex++; } while ( userInput != 99 ) message +='You entered the following:\n'; read more..

  • Page - 52

    ChapTer 2 ■ DaTa anD DeCisions 48 Now let’s change it again, so that you don’t break out of the loop but instead just ignore the user’s input and keep looping, using the continue statement: <html> <body> <script type="text/javascript"> var userNumbers = new Array( ); var userInput; var arrayIndex = 0; read more..

  • Page - 53

    49 Chapter 3 From DHTML to DOM Scripting In this chapter, you’ll learn what DHTML was, why it is regarded as a bad way to go nowadays, and what modern techniques and ideas should be used instead. You’ll learn what functions are and how to use them. You’ll also hear about variable and function scope and some state-of-the-art best practices that’ll teach your read more..

  • Page - 54

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 50 • High maintenance: Because most of the look and feel of the site or application was kept in the script, any change meant you needed to know at least basic JavaScript. Because JavaScript was developed for several different browsers, you needed to apply the change in all of the different scripts targeted to each browser. read more..

  • Page - 55

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 51 • The content layer: Is stored on the server and consists of all the text, images, and multimedia content that are used on the site (XML, database, media assets). • The business logic layer (or back end): Runs on the server and determines what is done with incoming data and what gets returned to the user. Behavior read more..

  • Page - 56

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 52 Note ■ While Firefox, Chrome, Safari, and opera display .js files as text, Microsoft internet explorer tries to execute them. if the file is assigned to a program (which you can tell by the icon), when you double-click, it will launch that program. if you drag it into the browser, read more..

  • Page - 57

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 53 A lot of older scripts use this information to determine whether a browser is capable of supporting their functionality: <script type="text/javascript"> if(navigator.appName.indexOf('Internet Explorer')!=-1 && browserVersion.indexOf('6')!=-1) { document.write('<p>This is MSIE! 6</p>'); } else { read more..

  • Page - 58

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 54 The if condition checks whether the browser gives you access to the images property, and it runs the code inside the condition only if that is the case. For a long time, scripts like these were the standard way of dealing with images. In newer browsers, a lot of the JavaScript image effects can be achieved with read more..

  • Page - 59

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 55 You might have a wonderful nude body, but it is insufficient in cold weather and might not • appeal to other people around you—you’ll ne ed something to cover it with. If there are clothes available, you can check which articles of clothing fit the weather, your • mood, the group of people you’ll be seeing this read more..

  • Page - 60

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 56 JavaScript and accessibility is holy war material. Many a battle between disgruntled developers and accessibility gurus is fought on mailing lists, in forums, and in chats, and the two sides all have their own—very good—arguments. The developers who had to suffer bad browsers and illogical assumptions by marketing managers (“I read more..

  • Page - 61

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 57 <script type="text/javascript"> // Valid examples var dynamicFunctionalityId = 'dynamic'; var parent_element2='mainnav'; var _base=10; var error_Message='You forgot to enter some fields: '; // Invalid examples var dynamic ID='dynamic'; // Space not allowed! var 10base=10; // Starts with a number read more..

  • Page - 62

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 58 Code Layout First and foremost, code is there to be converted by the interpreter to make a computer do something—or at least this is a very common myth. The interpreter will swallow the code without a hiccup when the code is valid—however, the real challenge for producing really good code is that a human will be read more..

  • Page - 63

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 59 return false; } } } } window.onload=addPopUpLink; Here they are with indentation and curly braces on new lines: function addPopUpLink() { var popupClass='smallpopup'; var popupMessage= ' (opens in new window)'; var pop,t; var as=document.getElementsByTagName('a'); read more..

  • Page - 64

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 60 Commenting Commenting is something that only humans benefit from—although in some higher programming languages, comments are indexed to generate documentation. (One example is the PHP manual, which at times is a bit cryptic for nonprogrammers exactly because of this.) Although commenting is not a necessity for the code to work—if read more..

  • Page - 65

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 61 /* addPopUpLink opens the linked document of all links with a certain class in a pop-up window and adds a message to the link text that there will be a new window */ function addPopUpLink() { // Assets of the link - the class to find out which link should // get the functionality and the read more..

  • Page - 66

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 62 There is no limit to how many parameters a function can have, but you should not use too many, because it can become rather confusing. If you check some DHTML code, you can find functions with 20 parameters or more, and remembering their order when calling those in other functions will make you almost want to simply read more..

  • Page - 67

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 63 if(!element) { element=document.getElementById(elementId); } element.appendChild(sourceLink); } Now, to use both these functions, you can have another one call them with the appropriate parameters: function linksInit() { var openLink=createLink('#','open'); appendLink(openLink); var closeLink=createLink('closed.html','close'); read more..

  • Page - 68

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 64 This is handy for Boolean conditions or very short values. For example, you can replace this long if condition with one line of code: // Normal syntax var direction; if(x<200) { direction=1; } else { direction=-1 } // Ternary operator var direction = x < 200 ? 1 : -1; Here are a few other examples: t.className = read more..

  • Page - 69

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 65 Variable and Function Scope Variables defined inside a function with a new var are valid only inside this function, not outside it. This might seem like a drawback, but it actually means that your scripts will not interfere with others—which could be fatal when you use JavaScript libraries or your own collections. Variables read more..

  • Page - 70

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 66 { // Some code }; myscript.validate=function() { // Some code }; </script> Notice that if you try to call the functions init() and validate(), you get an error, because they don’t exist any longer. Instead, you need to use myscript.init() and myscript.validate(). Wrapping all your read more..

  • Page - 71

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 67 As you can see, all the functions are contained as methods inside the dynamicLinks object, which means that if you want to call them, you need to add the name of the object before the function name. Another way of handling functions is to have them nested. The outer function would have a name, and the inner read more..

  • Page - 72

    CHapTer 3 ■ FroM DHTML To DoM SCripTing 68 Keep your code self-contained, and don’t use any global variables that might interfere with • other scripts. Code with the idea in mind that you will have to hand this code over to someone else • to maintain. This person might be you in three months’ time, and you should be able to immediately understand what is read more..

  • Page - 73

    69 Chapter 4 HTML and JavaScript In this chapter, you finally get your hands dirty in real JavaScript code. You’ll learn how JavaScript interacts with the page structure—defined in HTML—and how to receive data and give back information to your visitors. I start with an explanation of what an HTML document is and how it is structured, and then I explain several ways read more..

  • Page - 74

    Chapter 4 ■ htML and JavaSCript 70 HTML elements are everything in the brackets, <>, with a star ting tag like <h1> followed by content and a closing tag of the same name—like </h1>. Each elemen t can have content in between the opening and the closing tags. Each element might have several attributes. The following example is a P element with an attribute read more..

  • Page - 75

    Chapter 4 ■ htML and JavaSCript 71 a QUICK WOrD ON XhtML Figure 4-1. An HTML document rendered by a browser Browsers use DOCTYPE to decide how to render documents. the previous version of htML (XhtML 4.01) had a longer DOCTYPE. One of the things that it described was whether it should render things in Quirks Mode or Standards Mode. as the name read more..

  • Page - 76

    Chapter 4 ■ htML and JavaSCript 72 Tip ■ You can access similar tools in Chrome, Safari, Opera, and internet explorer. not only can you see how the document is represented, you can also edit the code and see the results directly in the browser. in the appendix, i’ll cover validation and debugging. Note ■ notice all the #text nodes between read more..

  • Page - 77

    Chapter 4 ■ htML and JavaSCript 73 It is very important to recognize HTML for what it is: HTML is structured content, not a visual construct like an image with elements placed at different coordinates. When you have a proper, valid HTML document, the sky is the limit, and you can access and change it via JavaScript. An invalid HTML document might trip up your read more..

  • Page - 78

    Chapter 4 ■ htML and JavaSCript 74 Suppose you want to tell the visitor to enter something in a search field before submitting a form. You could use an alert for that: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Search example</title> <script type="text/javascript"> function checkSearch() read more..

  • Page - 79

    Chapter 4 ■ htML and JavaSCript 75 Alerts do not return any information to the script—they simply give a message to the user and stop any further code execution until the OK button is activated. This is different for prompt() and confirm(). The former allows visitors to enter something, and the latter asks users to confirm an action. Tip ■ as a debugging read more..

  • Page - 80

    Chapter 4 ■ htML and JavaSCript 76 else { return true; } } Notice that confirm() is a method that returns a Boolean value (true or false) depending on whether the visitor activates OK or Cancel. Confirm dialogs are an easy way to stop visitors from taking really bad steps in web applications. Although they are not the prettiest way of read more..

  • Page - 81

    Chapter 4 ■ htML and JavaSCript 77 You can use this functionality to allow a visitor to change a value before sending a form to the server: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Date example</title> <script type="text/javascript"> function checkDate() { read more..

  • Page - 82

    Chapter 4 ■ htML and JavaSCript 78 Quick Review You can create pretty nifty JavaScripts using the prompt(), alert(), and confirm() methods, and they have some points in their favor: They are easy to grasp, because they use the functionality and look and feel of the browser and • offer a richer interface than HTML. (Specifically, the alert sound, when present, can help read more..

  • Page - 83

    Chapter 4 ■ htML and JavaSCript 79 If you go back to the HTML example we used earlier, you can write a small JavaScript example that shows how to use these two methods: <!doctype html> <html> <head> <meta charset="UTF-8"> <title>DOM Example</title> <script src="exampleFindElements.js"></script> </head> <body> <h1>Heading</h1> read more..

  • Page - 84

    Chapter 4 ■ htML and JavaSCript 80 You can achieve this by calling a function when the document has finished loading. The document has finished loading when the DOMContentLoaded event of the document object gets triggered. This event tells JavaScript that the structure of the page (the DOM) is ready for your code to work with it, and when it’s ready, call the read more..

  • Page - 85

    Chapter 4 ■ htML and JavaSCript 81 The length property also allows you to loop through elements and change all of them, one after the other: var linkItems = document.getElementsByTagName('li'); for(var i = 0; i < linkItems.length; i++) { // Do something... } Element IDs need to be unique to the document; therefore, the return value of getElementById() is a single read more..

  • Page - 86

    Chapter 4 ■ htML and JavaSCript 82 <li>List 2</li> <li><a href="http://www.google.com">Linked List Item</a></li> <li>List 4</li> </ul> <p class="paraStyle">Paragraph</p> <p class="paraStyle">Paragraph</p> </body> All the indented elements are children of the BODY. H1, H2, UL, and P are siblings, and the LI elements read more..

  • Page - 87

    Chapter 4 ■ htML and JavaSCript 83 The shortcut properties • yourElement.firstChild and yourElement.lastChild are easier versions of yourElement.childNodes[0] and yourElement.childNodes[yourElement. childNodes.length-1] and make it quicker to reach them. You can check whether an element has any children by calling the method • hasChildNodes(), which returns a Boolean value. Returning to read more..

  • Page - 88

    Chapter 4 ■ htML and JavaSCript 84 From the Children to the Parents You can also navigate from child elements back to their parents, via the parentNode property. First let’s make it easier for you to reach the link—by adding an ID to it: <ul id="eventsList"> <li>List</li> <li>List</li> <li> <a id="linkedItem" read more..

  • Page - 89

    Chapter 4 ■ htML and JavaSCript 85 while(parentElm.className != "dynamic") { parentElm = parentElm.parentNode; } However, this loop will end in an "TypeError: Cannot read property 'className' of null" error when there is no element with the right class. If you tell the loop to stop at the body, you can avoid that error: var myLinkItem = read more..

  • Page - 90

    Chapter 4 ■ htML and JavaSCript 86 alert(getTextContent(first)); alert(getTextContent(last)); } function lastSibling(node){ var tempObj=node.parentNode.lastChild; while(tempObj.nodeType!=1 && tempObj.previousSibling!=null) { tempObj=tempObj.previousSibling; } return (tempObj.nodeType==1)?tempObj:false; } function firstSibling(node) { var tempObj=node.parentNode.firstChild; read more..

  • Page - 91

    Chapter 4 ■ htML and JavaSCript 87 The checking script more or less stays the same as it was before—the difference is that you use the SPAN as a means of displaying the error: function checkDate(){ var dateField=document.getElementById('date'); if(!dateField){return;} var errorContainer=dateField.parentNode.getElementsByTagName("span")[0]; if(!errorContainer){return;} read more..

  • Page - 92

    Chapter 4 ■ htML and JavaSCript 88 Next is the validation of the field. Read the value of the date field, and check whether there is an entry. If there is no entry, the error message will be that the visitor should enter a date. If there is a date, but it is in the wrong format, the message will indicate so. var dateValue=dateField.value; if(dateValue=='') read more..

  • Page - 93

    Chapter 4 ■ htML and JavaSCript 89 Changing Attributes of Elements Once you reach the element you want to change, you can read and change its attributes in two ways: in an older way, having you talk directly to the elements; and in another way, using DOM methods. Older and newer user agents allow you to get and set element attributes as object properties: var read more..

  • Page - 94

    Chapter 4 ■ htML and JavaSCript 90 Creating, Removing, and Replacing Elements DOM also provides methods for changing the structure of the document you can use in an HTML/JavaScript environment. (There are more if you do XML conversion via JavaScript.) Not only can you change existing elements, you also can create new ones and replace or remove old ones as well. These read more..

  • Page - 95

    Chapter 4 ■ htML and JavaSCript 91 4. If it is the case, create a new link with a text node. 5. Set the node value of the text node to the value of the INPUT element. 6. Set the href of the link to javascript:document.forms[0].submit(), which allows you to submit the form when you click on the link. 7. Replace the input element with the link. Note read more..

  • Page - 96

    Chapter 4 ■ htML and JavaSCript 92 However, the function has one major flaw: it will fail when there are more input elements following the Submit button. Change the HTML to have another input after the Submit button: <form action="nogo.php" method="post"> <p> <label for="Name">Name:</label> <input type="text" id="Name" read more..

  • Page - 97

    Chapter 4 ■ htML and JavaSCript 93 This version of the script will not fail, and it replaces both buttons with links. Note ■ there is one usability aspect of forms that this script will break: you can submit forms by pressing the enter button when there is a Submit button in them. When you remove all Submit buttons, this will not be possible any longer. read more..

  • Page - 98

    Chapter 4 ■ htML and JavaSCript 94 You then write a script that simply removes it and even use this opportunity to test for DOM support at the same time: <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Example: Replacing noscript</title> <script type="text/javascript"> function noscript() { read more..

  • Page - 99

    Chapter 4 ■ htML and JavaSCript 95 Shortening Your Scripts via InnerHTML Microsoft implemented the nonstandard property innerHTML quite early in the development of Internet Explorer. It is now supported by most browsers; there has even been talk of adding it to the DOM standard. What it allows you to do is define a string containing HTML and assign it to an object. read more..

  • Page - 100

    Chapter 4 ■ htML and JavaSCript 96 DOM Summary: Your Cheat Sheet That was a lot to take in. It might be good to have all the DOM features you need in one place to copy and have on hand, so here you go: Reaching elements in a document • • document.getElementById('id'): Retrieves the element with the given id as an object • document.getElementsByTagName('tagname'): read more..

  • Page - 101

    Chapter 4 ■ htML and JavaSCript 97 DOMhelp: Your Own Helper Library The most annoying thing when working with the DOM is browser inconsistencies—especially when this means you have to test the nodeType every time you want to access a nextSibling, because the user agents for very old browsers might or might not read the line break as its own text node. Therefore, read more..

  • Page - 102

    Chapter 4 ■ htML and JavaSCript 98 You already encountered the last and first sibling functions earlier in this chapter; the only thing that was missing in those examples was a test for whether there really is a previous or next sibling to check before trying to assign it to the temporary object. Each of these two methods checks for the existence of the sibling in read more..

  • Page - 103

    Chapter 4 ■ htML and JavaSCript 99 while(tempObj.nodeType!=3 && tempObj.nextSibling!=null ||reg.test(tempObj.nodeValue)) { tempObj=tempObj.nextSibling; } if(tempObj.nodeType==3){tempObj.nodeValue=txt}else{return false;} }, The next two helper methods help you with the common tasks of creating a link with a target and text inside it and creating an element with text read more..

  • Page - 104

    Chapter 4 ■ htML and JavaSCript 100 The final set of methods is there to simulate a programmable JavaScript debug console. Using alert() as a means to display values is handy, but it can become a real pain when you want to watch changes inside a large loop—who wants to press Enter 200 times? Instead of using alert(), you add a new DIV to the document and read more..

  • Page - 105

    101 Chapter 5 Presentation and Behavior (CSS and Event Handling) In the last chapter, you took apart an HTML document to see what was under the hood. You fiddled with some of the cables, exchanged some parts, and got the engine in pristine condition. Now it is time to take a look at how to give the document a new lick of paint with Cascading Style Sheets read more..

  • Page - 106

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 102 <address> Awesome Web Production Company<br> Going Nowhere Lane 0<br> Catch 22<br> N4 2XX<br> England<br> </address> </body> </html> styleChange.js var sc = { init:function(){ sc.head = document.getElementsByTagName('h3')[0]; if(!sc.head){return;} read more..

  • Page - 107

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 103 Note ■ You might have encountered scripts in the past that use element.style.display='block' as the opposite of none. this works for most elements, but simply setting the display value to nothing resets it to the initial display value— which does not necessarily have to be block; it could read more..

  • Page - 108

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 104 Note ■ a reference guide that includes vendor-prefixed Css is on the Mozilla Developer network at https://developer.mozilla.org/en-US/docs/CSS/CSS_Reference. You can read and write style properties using getAttribute() and setAttribute(); however, if you write them, it might be quicker to simply set the read more..

  • Page - 109

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 105 You can achieve this separation by dynamically changing the class attribute of elements. That way, you can apply or remove style settings defined in your site’s style sheet. The CSS designer does not have to worry about your script code, and you don’t have to know about all the problems read more..

  • Page - 110

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 106 break; case 'remove': var rep=o.className.match(''+c1)?''+c1:c1; o.className=o.className.replace(rep,''); break; case 'check': var found=false; var temparray=o.className.split(''); for(var i=0;i<temparray.length;i++){ read more..

  • Page - 111

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 107 </address> </body> </html> The style sheet contains, among others, a class called hide that will hide any element it gets applied to. This is done is by using a CSS clip. The clip defines the visible areas of this absolutely positioned element. For the read more..

  • Page - 112

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 108 sc.head.replaceChild(collapseLink,sc.head.firstChild); DOMhelp.addEvent(collapseLink,'click',sc.peekaboo,false) collapseLink.onclick=function(){return;} // Safari fix }, peekaboo:function(e){ if(DOMhelp.cssjs('check',sc.ad,sc.hidingClass)){ DOMhelp.cssjs('remove',sc.ad,sc.hidingClass) } else read more..

  • Page - 113

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 109 DOMhelp.cssjs('add',sc.ad,sc.hidingClass); var t=DOMhelp.getText(sc.head); var collapseLink=DOMhelp.createLink('#',t); sc.head.replaceChild(collapseLink,sc.head.firstChild); DOMhelp.addEvent(collapseLink,'click',sc.peekaboo,false) collapseLink.onclick=function(){return;} // Safari fix }, read more..

  • Page - 114

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 110 /* JS enabled */ body.dynamic address{ background:#fff; border:none; font-style:normal; padding:.5em; border-top:1px solid #ccc; } body.dynamic h3{ padding-bottom:.5em; background:#fff; border:none; } body.dynamic h3 a{ color:#369; } /* dynamic classes */ .hide{ position: absolute !important; read more..

  • Page - 115

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 111 This works nicely if your site is not overly complex and does not have many dynamic elements. For more complex sites, you could use a different style sheet for the non-JavaScript versions and the JavaScript versions and add the latter via JavaScript. This also has an added benefit: the low-level user read more..

  • Page - 116

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 112 <h3>Contact Details</h3> <address> Awesome Web Production Company<br> Going Nowhere Lane 0<br> Catch 22<br> N4 2XX<br> England<br> </adress> </body> </html> The script checks for DOM support and adds a new link element pointing to the high-level read more..

  • Page - 117

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 113 The head of the HTML example is the following after the script has executed. (You can test this in Firefox by selecting the whole document via Ctrl+A or Cmd+A and then right-clicking anywhere and choosing View Selected Source.) exampleStyleSheetChange.html after script read more..

  • Page - 118

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 114 stylemenu.appendChild(tempLI); stylemenu.id=switcher.menuID; You loop through all the LINK elements in the document. For each element, test for the value of its rel attribute. If the value is neither stylesheet nor alternate stylesheet, skip this LINK element. This is necessary to avoid other read more..

  • Page - 119

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 115 if(links[i].getAttribute('rel')!='stylesheet'&& links[i].getAttribute('rel')!='alternate stylesheet'){ continue; } var title=o.firstChild.nodeValue; if(links[i].getAttribute('title')!=title){ links[i].disabled=true; } else read more..

  • Page - 120

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 116 sc.head.replaceChild(collapseLink,sc.head.firstChild); DOMhelp.addEvent(collapseLink,'click',sc.peekaboo,false) collapseLink.onclick=function(){return;} // Safari fix }, peekaboo:function(e){ if(DOMhelp.cssjs('check',sc.ad,sc.hidingClass)){ DOMhelp.cssjs('remove',sc.ad,sc.hidingClass) } else read more..

  • Page - 121

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 117 cssClassNames.js css={ // Hide elements hide:'hide', // Indicator for support of dynamic scripting // will be added to the body element supported:'dynamic' } You can apply it to the document just like any of the other scripts in use: exampleDynamicStylingCSSObject.html <head> <meta read more..

  • Page - 122

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 118 In this example, the cssClassNames.js file uses object literal notation. You could go even further and get rid of the comments if you use JSON (http://www.json.org/), which is a format for transferring data from one program or system to another. You will hear more about JSON and its merits in read more..

  • Page - 123

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 119 Browser support for CSS has improved, but as new features are added you might run into things like vendor prefixes: background-color:#444444; background-image: -webkit-gradient(linear, left top, left bottom, from(#444444), to(#999999)); /*Safari 4+,Chrome*/ background-image:-webkit-linear-gradient(top,#444444,#999999); /*Chrome read more..

  • Page - 124

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 120 Let’s start with a list of news items, each containing a heading, a “teaser” para graph and a “more” link . exampleColumnHeightIssue.html (with dummy content) <ul id="news"> <li> <h3><a href="news.php?item=1">News Title 1</a></h3> <p>Description 1</p> <p read more..

  • Page - 125

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 121 As you can see in the example, each column has a different height, and neither the paragraphs nor the “more” links are in the same position. This makes the design look uneven and can confuse the reader. There might be a CSS way to fix this issue (I am always impressed what kind of hacks read more..

  • Page - 126

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 122 fixColumnHeight.js (excerpt) fixcolumns={ highest:0, moreClass:'more', init:function(){ if(!document.getElementById || !document.createTextNode){return;} fixcolumns.n=document.getElementById('news'); if(!fixcolumns.n){return;} fixcolumns.fix('h3'); fixcolumns.fix('p'); read more..

  • Page - 127

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 123 The fixElements() method then applies the maximum height to all the elements with the given name. Notice that you need to test for the class determining the “more” link s; otherwise, the links would get the same height as the highest content paragraph. fixElements:function(elm){ var read more..

  • Page - 128

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 124 In IE 6, you will not get this effect, because it does not support :hover for list items. However, it supports JavaScript, which means that you can use the cssjs method to add a class dynamically when the user hovers the pointer over the list items: listItemRollover.css (excerpt) #news{ read more..

  • Page - 129

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 125 listItemRollover.js (excerpt) newshl={ overClass:'over', init:function(){ if(!document.getElementById || !document.createTextNode){return;} var newsList=document.getElementById('news'); if(!newsList){return;} var newsItems=newsList.getElementsByTagName('li'); for(var i=0;i<newsItems.length;i++){ read more..

  • Page - 130

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 126 Then you need to apply the events to the links inside the list items and change the class of their parent node’s parent node (because the link in this example is either in a heading or in a paragraph): listItemDoubleRollover.js newshl={ // CSS classes overClass:'over', // Hover state read more..

  • Page - 131

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 127 Using JavaScript, you can also make the whole news item clickable, and this is where more events come into play. If You Have a Hammer, Everything Looks Like a Nail These few examples should make it clear to you that JavaScript and the DOM are very powerful when it comes to making the browser read more..

  • Page - 132

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 128 Changing the Document’s Behavior via Event Handling Event handling is probably the best thing JavaScript offers to a user-interface-focused developer. It is also one of the most confusing JavaScript topics—not because it is complex, but because there have been different ways to implement them. I will read more..

  • Page - 133

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 129 You hijack the event of this element for your script exclusively—methods of other scripts • trying to use this element for other events will not work any longer. Unless you defined triggerLink as a global variable or object property, the function infoWindow() needs to find the trigger element read more..

  • Page - 134

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 130 If you want to apply the function infoWindow() to the link via addEventListener(), you use the following: var triggerLink=document.getElementById('info'); triggerLink.addEventListener( 'click', infoWindow, false); If you want to add a hover effect by calling the function highlight() when the mouse is over the read more..

  • Page - 135

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 131 case 'mouseover': // Code to deal with the user hovering over the link break; case 'mouseout': // Code to deal with the user leaving the link break; } You could also check the element the event occurred at by checking its nodeName. read more..

  • Page - 136

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 132 If you now assign a mouseover event to the links in the list, hovering the mouse over them will also trigger any event listener that might be on the paragraphs, the list items, the list, and all the other elements above that in the node tree right up to the document body. As an example, read more..

  • Page - 137

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 133 the output will be p was clicked Event bubbling is not really that problematic, because you are not often likely to assign different listeners to embedded elements instead of to their parents. However, if you want to learn more about event bubbling and the order of what happens when an event occurs, read more..

  • Page - 138

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 134 width: 1px !important; overflow: hidden; } li.current{ background:#ccf; } li.current h3{ background:#69c; } The script for collapsing the elements is not complex, but it uses all the event-handling elements I talked about: newsItemCollapse.js newshl={ // CSS classes overClass:'over', // read more..

  • Page - 139

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 135 hover:function(e){ var hl=e.target.parentNode.parentNode; var action=e.type=='mouseout'?'remove':'add'; DOMhelp.cssjs(action,hl,newshl.overClass); } } window.addEventListener ('load',newshl.init,false); The results are clickable news headings that show associated news excerpts when you click them. The read more..

  • Page - 140

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 136 hl.addEventListener('mouseover',newshl.hover,false); hl.addEventListener('mouseout',newshl.hover,false); } You hide all paragraphs inside the list item by applying the hiding class to them: newsItemCollapse.js (excerpt) var ps=newsList.getElementsByTagName('p'); for(i=0;i<ps.length;i++){ DOMhelp.cssjs('add',ps[i],newshl.hideClass); } read more..

  • Page - 141

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 137 The hover method grabs the list item via parentNode and checks the type of the event that was used to call the method. If the event was mouseout, it defines the action as remove; otherwise, it defines the action as add. It then applies or removes the class from the list item: read more..

  • Page - 142

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 138 The function uses one more parameter than addEventListener(), which is the element itself. It tests whether addEventListener() is supported and simply returns true when it is able to attach the event in the W3C-compliant way. Otherwise, it checks whether attachEvent() is supported (effectively meaning IE read more..

  • Page - 143

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 139 Safari has a nasty bug (or feature—one is never sure): if you click a link, it does not send the link as the target; instead, it sends the text node contained in the link. A workaround is to check whether the element’s node name is really a link: read more..

  • Page - 144

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 140 if (e && e.stopPropagation && e.preventDefault){ e.stopPropagation(); e.preventDefault(); } } Using these helper methods should allow you to handle events unobtrusively and across browsers. The way around this for versions of Safari prior to 5.1 is to add another dummy function read more..

  • Page - 145

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 141 DOMhelp.cssjs(action,hl,newshl.overClass); } } DOMhelp.addEvent(window,'load',newshl.init,false); Note ■ hl.onclick = DOMhelp.safariClickFix; could be a simple hl.onclick = function(){return false;}; however, it will be easier to search and replace this fix once the safari development team has sorted read more..

  • Page - 146

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 142 The next change is in the toggleNews() method. There you replace the loop with a simple if condition that checks whether the current class is applied to the list item and replaces hide with current if that is the case and current with hide if it isn’t. This shows or hides all the read more..

  • Page - 147

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 143 If something is likely to change in the future, like the Safari • stopPropagation() hack, you should put it in its own method. The next time you see the code and you spot this seemingly useless method, you’ll remember what was going on. Don’t rely on HTML too much. It is always the first read more..

  • Page - 148

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 144 <script type="text/javascript" src="DOMhelp.js"></script> <script type="text/javascript" src="keyChecking.js"></script> </head> <body> <p class="ex">Keychecking example, try to enter anything but numbers in the form field below.</p> <h1>Get Chris Heilmann's book read more..

  • Page - 149

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 145 if (!document.getElementById || !document.createTextNode) { return; } var voucher=document.getElementById('Voucher'); if(!voucher){return;} voucherCheck.v=voucher; DOMhelp.addEvent(voucher, 'keyup', voucherCheck.checkKey, false); }, checkKey:function(e){ if(window.event){ read more..

  • Page - 150

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 146 The checkKey method determines whether window.event or the event object is in use and reads out the keyCode in the appropriate manner: keyChecking.js (excerpt) checkKey:function(e){ if(window.event){ var key = window.event.keyCode; } else if(e){ var key=e.keyCode; read more..

  • Page - 151

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 147 Note ■ normally, it would be enough to check whether the field content is a number on every keyup event, but this demonstrates the power you have with keyboard events. If you want to read keyboard combinations with Shift, Ctrl, or Alt, you need to check for the shiftKey, ctrlKey, or read more..

  • Page - 152

    Chapter 5 ■ presentatiOn anD BehaviOr (Css anD event hanDling) 148 Summary You’ve made it to the end of this chapter, and I hope it was not too much information at once. In the first half, I talked about the interaction of CSS and JavaScript, covering the following: How to change presentation in JavaScript via the style collection • How to help CSS designers by read more..

  • Page - 153

    149 Chapter 6 Common Uses of JavaScript: Images and Windows If you read the last few chapters, you should be well equipped now with your knowledge of JavaScript and its interaction with cascading style sheets (CSS) and HTML. Now you will learn about some of the most common uses of JavaScript on the Web these days, and we’ll go through some examples. In these read more..

  • Page - 154

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 150 Basics of Image Scripting In JavaScript, you can reach and amend images in two ways: the DOM-2 way via getElementsByTagName() and getElementById(), or in an older way that involves the images collection that is stored in a property of the document object. As an example, let’s take an HTML read more..

  • Page - 155

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 151 You can use these properties to access and change images dynamically. If you open the example document exampleImageProperties.html in a browser, you can read and write the properties of the demonstration image as Figure 6-1 shows. Figure 6-1. Reading and writing the properties of an image Note ■ read more..

  • Page - 156

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 152 You’ll see an example of this soon in the “Rollover Effects” section: function simplePreload() { var args = simplePreload.arguments; document.imageArray = new Array( args.length ); for(var i = 0; i < args.length; i++ ) { document.imageArray[i] = new Image; document.imageArray[i].src read more..

  • Page - 157

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 153 onmouseout="rollover('contact', 'but_contact.gif')"> <img src="but_contact.gif" name="contact" width="103" height="28" alt="Contact Us" border="0"> </a> JavaScript function rollover( img, url ) { document.images[img].src=url; } The problem with rollovers was (and read more..

  • Page - 158

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 154 init : function(){}, roll : function( e ){} } DOMhelp.addEvent( window, 'load', ro.init, false ); Let’s start fleshing out the skeleton. First up are the properties and the init method. In it, you predefine a variable called oversrc and store all the images of the document in an array read more..

  • Page - 159

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 155 The roll method retrieves the image the event occurred on via getTarget(e) and stores its src property in a variable called s. You then test which of the events occurred by reading out the event type. If the event type was mouseover, you replace the full stop in the file name with the read more..

  • Page - 160

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 156 The same problems occurred—images had to get loaded before they were displayed, which made the rollover effect flicker or not happen at all. The solution was to take one single image for both states and use the background-position property to change the location of the image, as shown in Figure read more..

  • Page - 161

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 157 Rollover Effects on Parent Elements Let’s take an HTML list and turn it into a snazzy navigation bar by adding a nice background image, and then make the links change the background image when the mouse hovers over them. The first thing you need is a background image with all the states of read more..

  • Page - 162

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 158 You start with an initialization method that checks for DOM support and whether the necessary list with the right ID is available: parentRollover.js (continued) init : function() { if( !document.getElementById || !document.createTextNode ) { return; } pr.nav = document.getElementById( pr.navId ); read more..

  • Page - 163

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 159 parentRollover.js (continued) roll : function( e ) { var pos; var t = DOMhelp.getTarget(e); while(t.nodeName.toLowerCase() != 'li' && t.nodeName.toLowerCase() != 'body') { t = t.parentNode; } Then you define the position needed to show the right background image. This position is read more..

  • Page - 164

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 160 In the roll() method, you check once again whether the event triggering the method was mouseover and add or remove a new dynamic class accordingly. This dynamically assigned and named class consists of the dynamicLink property value and the current index plus one (because it is easier for read more..

  • Page - 165

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 161 Embedded Slide Shows Probably the easiest way to add a slide show to a page is to add all the images as a list. You can then use JavaScript to turn this list into a slide show by hiding and showing the different list items with the embedded images. The demo document read more..

  • Page - 166

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 162 All future maintainers have to do to change the order of the images or add or delete images is change the HTML. There is no need to change the JavaScript at all. As long as you supply an appropriate style sheet, visitors without JavaScript will get all the images displayed as shown in read more..

  • Page - 167

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 163 As for methods, all you need (apart from the helper methods contained in DOMhelp) is a global initialization method, a method to initialize each slide show, and a method to show a slide. All of this together makes up the skeleton of your script: photoListInlineSlides.js (skeleton) inlineSlides = { read more..

  • Page - 168

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 164 photoListInlineSlides.js (excerpt) init : function() { if( !document.getElementById || !document.createTextNode ) { return; } var uls = document.getElementsByTagName('ul'); for( var i = 0; i < uls.length; i++ ) { if( !DOMhelp.cssjs('check', uls[i], nlineSlides.slideClass ) ) { read more..

  • Page - 169

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 165 The initSlideShow() method gets each slide show list as a parameter called lst. First, define the variables you’ll use with the var keyword to make sure they don’t overwrite global variables with the same name. Then create a new paragraph element to host the forward and backward links and the read more..

  • Page - 170

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 166 photoListInlineSlides.js (continued) lst.fwd = DOMhelp.createLink('#', ' ' ); lst.fwd.innerHTML = inlineSlides.forwardsLabel; DOMhelp.addEvent(lst.fwd, 'click', inlineSlides.showSlide, false ); p.appendChild(lst.fwd ); The method concludes with taking the list item that corresponds to the currentSlide property and adding the show read more..

  • Page - 171

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 167 Determine whether the link that was activated was the forward link by comparing the target with the fwd property of the list, and then increment or decrement the counter accordingly. If the counter is larger than 0, remove the hide class from the backward link; otherwise, add this class, effectively read more..

  • Page - 172

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 168 Preventing this issue is rather easy though: all you need to amend is the showSlide() method so that nothing is done when the target that was clicked has the hide CSS class assigned to it. And when fixing that, you might as well add the Safari fix to cancel the default action of the newly read more..

  • Page - 173

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 169 replace( /#/, lst.currentSlide + 1 ); temp = temp.replace( /%/, o.getElementsByTagName('li').length ); lst.count.appendChild( document.createTextNode( temp ) ); p.appendChild(lst.count ); lst.fwd=DOMhelp.createLink('#', ' ' ); lst.fwd.innerHTML = inlineSlides.forwardsLabel; read more..

  • Page - 174

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 170 Dynamic Slide Shows Let’s take another HTML list and turn it into an example of a dynamic slide show. Start with the HTML—this time a list containing thumbnail images linked to larger images: exampleMiniSlides.html <ul class="minislides"> <li> <a href="pictures/thumbs/cat2.jpg"> read more..

  • Page - 175

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 171 Visitors without JavaScript will get only a row of images linking to larger images, as shown in Figure 6-10. Figure 6-10. The slide show with small preview images without JavaScript Again, let’s plan the skeleton of the script: you define a class to recognize which lists are to become slide shows, read more..

  • Page - 176

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 172 .minislides li{ padding:1px; } .minislides li.photo{ clear:both; padding-top:0; } First, you do a global reset on anything inside the list with the right class and the list itself. A global reset means setting all margins and paddings to 0 and the borders and list styles to none. This read more..

  • Page - 177

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 173 Then you grab the first image in the list and read its alternative text stored in the alt attribute. Add this text as the alternative text to the new image, add the text stored in the alternativeText property to it, and store the resulting string as a title attribute of the new image: read more..

  • Page - 178

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 174 For now, here are some things to remember about images and JavaScript: You can do a lot of preloading with the image objects, but it is not a bulletproof approach. • Browser cache settings, broken image links, and proxy servers might mess with your preload script. There are libraries that can help read more..

  • Page - 179

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 175 Other browsers like Microsoft Internet Explorer 7 or Opera 8 disallow hiding the location bar in new windows and can impose size and position constraints on new windows. Note ■ This is a point of agreement between different browser manufacturers that want to stop security vulnerabilities. Opening read more..

  • Page - 180

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 176 For example, if you want to obtain the inner size of a window, you could use some of these properties: exampleWindowProperties.html (excerpt) function winProps() { var winWidth = window.outerWidth; var winHeight = window.outerHeight; var docWidth = window.innerWidth; var docHeight = window.innerHeight; read more..

  • Page - 181

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 177 User Feedback Methods The user feedback methods listed here are covered in detail in Chapter 4: • alert('message'): Displays an alert • confirm('message'): Displays a dialog to confirm an action • prompt('message', 'preset'): Displays a dialog to enter a value Opening New Windows The opening and closing read more..

  • Page - 182

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 178 To open a window that is 200 pixels wide and high and 100 pixels from the top-left corner of the screen, and then load into it the document grid.html, you have to set the appropriate properties as shown here: var windowprops = "width=200,height=200,top=100,left=100"; You can try to open the window read more..

  • Page - 183

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 179 Unless you use nontransitional XHTML or strict HTML (where target is deprecated), you can also use the target attribute with a value of _blank to open a new window regardless of the availability of JavaScript. It is good practice, then, to tell the visitor that the link is going to open in a read more..

  • Page - 184

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 180 label = document.createTextNode( poplinks.popupLabel ); allLinks[i].appendChild( label ); DOMhelp.addEvent( allLinks[i], 'click',poplinks.openPopup, false ); allLinks[i].onclick = DOMhelp.safariClickFix; } }, The openPopup() method retrieves the event target, makes sure that it was a read more..

  • Page - 185

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 181 If you want to reach the initial window from any of the documents in the pop-ups, you can do this via var parentWin = window.opener; If you want to reach the second window from the first window, you also need to go through the window.opener, because the second window was opened from this read more..

  • Page - 186

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 182 Figure 6-13. Changing the window position and dimension Animation with Window Intervals and Timeouts You can use the setInterval() and setTimeout() window methods to allow for the timed execution of code. setTimeout means you wait a certain time before executing the code (once only); setInterval() read more..

  • Page - 187

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 183 Classic examples for the use of these methods are news tickers, clocks, and animation. However, you can also use them to make your site less obtrusive and more user beneficial. One example of this is a warning message that vanishes after a certain amount of time. The demo exampleTimeout.html shows read more..

  • Page - 188

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 184 warn.w = document.getElementById('warning'); if( !warn.w ){ return; } DOMhelp.cssjs('add', warn.w, 'warning'); var temp = DOMhelp.createLink('#', 'remove warning'); DOMhelp.addEvent( temp, 'click', warn.removeWarning, false ); temp.onclick = DOMhelp.safariClickFix; read more..

  • Page - 189

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 185 However, for web sites this is not formulated as clearly. The World Wide Web Consortium (W3C) accessibility guidelines, on the other hand, state explicitly in a level-two priority that you should avoid any movement in web pages: Until user agents allow users to freeze moving content, avoid movement in read more..

  • Page - 190

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 186 autoSlideShow.js (excerpt) autoSlides = { // CSS classes slideClass : 'slides', dynamicSlideClass : 'dynslides', showClass : 'show', slideCounterClass : 'slidecounter', The other properties change slightly. Instead of backward and forward labels, you now need play and stop labels. The counter read more..

  • Page - 191

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 187 DOMhelp.cssjs('swap', uls[i], autoSlides.slideClass,_autoSlides.dynamicSlideClass ); uls[i].currentSlide = 0; uls[i]. showIndex = i; autoSlides.initSlideShow( uls[i] ); autoSlides.slideLists.push( uls[i] ); } }, The initSlideShow() method does not differ much from the method of read more..

  • Page - 192

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 188 You use setInterval() with the delay defined in the autoSlides.delay property and store it in the loop property before changing the content of the link that was activated to the Stop button: autoSlides.js (continued) if( !parentList.loop ) { var loopCall = "autoSlides.showSlide('" + parentList.showIndex + read more..

  • Page - 193

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 189 Show the slide by retrieving the list element and adding the show class. Update the counter, and reset the currentSlide property of the list to the new list element: autoSlides.js (continued) count++; if( count == photoCount ){ count = 0 }; photo = read more..

  • Page - 194

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 190 var p = document.getElementById('back'); if( p ) { var newa = document.createElement('a'); newa.setAttribute('href', '#'); newa.appendChild( document.createTextNode('back to previous page') ); newa.onclick = function() { window.back();return false; } p.replaceChild( newa, read more..

  • Page - 195

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 191 The CSS designer can style the ad for the non-JavaScript version, and the script will add a class to allow the ad to show up above the main content. If you call the class dyn, the CSS might look like this: layerAd.css (excerpt) #layerad{ margin:.5em; padding:.5em; } #layerad.dyn{ read more..

  • Page - 196

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 192 The killAd() method removes the ad from the document and cancels the link’s default behavior: layerAd.js (continued) killAd : function( e ) { ad.offer.parentNode.removeChild( ad.offer ); DOMhelp.cancelClick( e ); } } DOMhelp.addEvent( window, 'load', ad.init, false ); You can test the read more..

  • Page - 197

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 193 popupClass:'popup', displayPrefix:'Hide', popContainer:null, The init() method checks for DOM support and loops through all the links of the document, testing whether they have the right CSS class to trigger the pop-up. For those that do, the method adds an event handler pointing to the read more..

  • Page - 198

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 194 newimg.setAttribute('src', t.getAttribute('href') ); document.body.appendChild( pop.popContainer ); pop.positionPopup( t ); If the popContainer already exists, all the method does is call the killPopup() method, reset the link to its original content, and remove the class that indicates that the photo is shown. read more..

  • Page - 199

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 195 picturePopup.js (continued) killPopup : function( e ) { pop.popContainer.parentNode.removeChild( pop.popContainer ); pop.popContainer = null; DOMhelp.cancelClick( e ); } } DOMhelp.addEvent( window, 'load', pop.init, false ); The result is that you can click any image pointing to a read more..

  • Page - 200

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 196 Including other documents via IFRAME elements is an easy and well-supported method, but it is not the most accessible way. What you could do instead is use a server-side language like PHP to retrieve the content of the document and include it in the current one, and use the same trick the layer read more..

  • Page - 201

    ChapTer 6 ■ COMMOn USeS Of JavaSCrIpT: IMageS anD WInDOWS 197 accidentally closing the window your web site needs. Years of unsolicited advertising and pop-ups have conditioned web surfers to immediately close new windows without even glancing at them. Employing timed execution of code via the window methods • setTimeout() and setInterval() is a bit like using read more..

  • Page - 202

    199 Chapter 7 JavaScript and User Interaction: Navigation and Forms In this chapter, I will talk about two more common uses of JavaScript: navigation and forms. Both involve a lot of user interaction and therefore need to be planned and executed thoughtfully. The success of a web site stands and falls with the ease of its navigation, and there is nothing more frustrating on read more..

  • Page - 203

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 200 This means you can create a slick interface that shows only a slice of the overall page content with JavaScript, but it also means that visitors without JavaScript will have to deal with the entire amount of data in the document. Before you go completely nuts on enhancing pages, turn off JavaScript read more..

  • Page - 204

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 201 <option value="http://wait-till-i.com">The author's blog</option> <option value="http://icant.co.uk">The author's other articles</option> <option value="http://onlinetools.org">Scripts and tools by the author</option> </select> </p> </form> Keyboard access is read more..

  • Page - 205

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 202 The server-side script to send non-JavaScript users to the other URI could be a simple header redirect in PHP: <?php header('Location: ' . $_POST['url']); ?> If the user has JavaScript enabled, she won’t have to do the round-trip to the server; instead, she’ll get sent to the other web site read more..

  • Page - 206

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 203 Using replace() can be quite annoying, because you break the user’s Back button functionality. She cannot go back to the current page when she doesn’t like the one you sent her to. The list of pages the user visited before reaching the current one is stored in the window.history object. This read more..

  • Page - 207

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 204 <h2><a id="info" name="info">Information about X</a></h2> [... content ...] <p class="back"> <a href="#toolinfotoc">Back to <acronym title="Table of Contents">TOC</acronym></a> </p> </div> <div read more..

  • Page - 208

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 205 Let’s start by defining the skeleton of the script. The main object of the script is called iv, for inner navigation—because in is a reserved word in JavaScript, and you want to keep it short. You’ll need several properties: A CSS class to define when the menu is JavaScript enhanced • A read more..

  • Page - 209

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 206 iv.parent = document.getElementById(iv.parentID); iv.toc = document.getElementById(iv.tocID); if(!iv.parent || !iv.toc) { return; } DOMhelp.cssjs('add', iv.parent, iv.dynamicClass); Store a possible URL hash in the variable loc, and start looping through all the links in the menu. Replacing the # in read more..

  • Page - 210

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 207 innerNav.js (continued) getSection : function(e) { var t = DOMhelp.getTarget(e); iv.showSection(t); }, The showSection() method retrieves the link object that was either clicked or defined in the init() method as the parameter o. The first task is to read the href attribute of this link and read more..

  • Page - 211

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 208 Simply applying a different style sheet turns the page into a tabbed interface, as you can see in exampleLinkedAnchorsTabs.html and in Figure 7-3. Figure 7-3. A tabbed interface created from an anchor—target list Figure 7-2. A panel interface created from an anchor—target list read more..

  • Page - 212

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 209 This is pretty neat for a short script; however, cleaning up the link href and retrieving the section every time the user clicks one of the options seems repetitive. A different approach to accomplishing the same task is to store the links and the sections in two associative arrays and simply read more..

  • Page - 213

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 210 Define the first link as the currently active link by storing it in the presetLink variable, and determine whether the anchor points to an existing element. If it does, store the element in the sections array and the link in the sectionLinks array. Note that this results in an associative read more..

  • Page - 214

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 211 There are more options for in-page navigation—for example, you could offer “previous” and “next” link s instead of “back” link s to go through the options. If you want to see a script that does that and also offers several tabbed navigations per page, you can check out DOMtab at read more..

  • Page - 215

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 212 <li><a href="#">Industry Partners</a></li> </ul> </li> <li><a href="#">Contact Us</a> <ul> <li><a href="#">Postal Addresses</a></li> <li><a href="#">Arrange read more..

  • Page - 216

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 213 Expecting this HTML structure allows you to create an Explorer-like expanding and collapsing menu. A menu item that contains other items should show or hide its child items when you click it. However, the logic of the script is probably a bit different from what you’d expect. For starters, you read more..

  • Page - 217

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 214 siteNavigation.js (skeleton) sn = { dynamicClass : 'dyn', showClass : 'show', parentClass : 'parent', openClass : 'open', navID : 'nav', init : function() {}, changeSection : function(e) {} } DOMhelp.addEvent(window, 'load', sn.init, false); The init() method defines a variable read more..

  • Page - 218

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 215 All the event listener method changeSection() needs to do is get the event target, test whether the first nested UL of the parent node has the show class applied to it, and remove that UL if that is the case. Furthermore, it needs to change the open class of the parent node to parent read more..

  • Page - 219

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 216 The demo page exampleIndicatorSiteNavigation.html shows what this looks like and how it works. The script does not have to change that much: siteNavigationIndicator.js (excerpt) sn = { dynamicClass : 'dyn', showClass : 'show', parentClass : 'parent', openClass : 'open', The first change is read more..

  • Page - 220

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 217 if(parentLI.getElementsByTagName('strong').length > 0) { DOMhelp.cssjs('add', parentLI, sn.openClass); DOMhelp.cssjs('add', nested[i], sn.showClass); parentLI.getElementsByTagName('a')[0].innerHTML = sn.openIndicator } } }, The difference in the changeSection() method is read more..

  • Page - 221

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 218 The content to be manipulated consists of a set of rows of the same HTML table, which has the class paginated. examplePagination.html (excerpt) <table class="paginated"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Artist</th> read more..

  • Page - 222

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 219 <tr> <th>2</th> <td>Monty Python</td> <td>The final Rip-Off</td> <td>Double CD with all the songs</td> </tr> [... and so on ...] </tbody> </table> You used pagination in the last chapter in the slide-show example, read more..

  • Page - 223

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 220 You use one method to initialize the script, one to generate the extra links and elements that you need, one to navigate around the “pages” (tha t is, hide the current result set and show the next), one to show the current page, and one to alter the pagination menu. init : read more..

  • Page - 224

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 221 Apply the dynamic class to the table and thus hide all the table rows. Call the createPaginationNav() method with a reference to the current table as a parameter to add the “previous” and “next” link s, and call showSection() with the table reference and 0 as parameters to show the first read more..

  • Page - 225

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 222 You couldn’t apply the event handlers earlier, because cloneNode() does not clone any handlers. Now you can apply all the handlers and the fixes for old versions of Safari to each of the links. The last change for this method is to store the counters in properties to make it easier for the read more..

  • Page - 226

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 223 pagination.js (excerpt) if(t == table.topNext || t == table.bottomNext){ start = table.current + pn.increase; } else if (t == table.topPrev || t == table.bottomPrev){ start = table.current - pn.increase; } pn.showSection(table, start); }, The showSection() method calls the read more..

  • Page - 227

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 224 pagination.js (excerpt) changePaginationNav : function(table, start){ if(start - pn.increase < 0) { table.bottomPrev.removeAttribute('href'); table.topPrev.removeAttribute('href'); } else { table.bottomPrev.setAttribute('href', '#'); table.topPrev.setAttribute('href', '#'); } If start plus read more..

  • Page - 228

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 225 You can use JavaScript to make large amounts of data, like deeply nested navigation menus, easier to grasp and presented to the user in bite-size chunks. However, don’t forget that some users will get all of the navigation without your script cutting it up into smaller servings. It might be a read more..

  • Page - 229

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 226 <p><label for="Message">Your Message</label></p> <p><textarea id="Message" name="Message" cols="20" rows="5"></textarea></p> </fieldset> <fieldset> <legend>Email options</legend> <p><input type="checkbox" name="copyMeIn" read more..

  • Page - 230

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 227 • method: The submission method of the form—either POST or GET • name: The name of the form as defined in the name attribute (not in the id!) • target: The target the form data should be sent to (which is important if you use frames or multiple windows) Form Methods The Form object read more..

  • Page - 231

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 228 Each element inside the collection has several properties; which ones are supported is dependent on the type of the element. I’ll now list all the properties and list the elements that support this property in parentheses. We’ll go through the different elements in detail later on in this chapter: read more..

  • Page - 232

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 229 Tip ■ It is a good idea to check the type of the element you are manipulating before trying to set attributes on it, in case they are not available for this element. a SELECT element, for example, does not have cols or rows attributes. Globally Supported Properties All form read more..

  • Page - 233

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 230 Developers used to do this to stop browsers from showing a blue box or a dotted border around the current link. This is a very bad idea, because a keyboard user wouldn’t know which element she is currently able to reach when pressing Enter. There are some legitimate reasons to use focus(); read more..

  • Page - 234

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 231 Text elements allow for a method called select(), which highlights all the text inside them to make it easier to copy and paste text examples. This is often seen as a feature in webzines or online documentation systems. Check Boxes Check boxes are a great way to offer an unambiguous “yes” or “ read more..

  • Page - 235

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 232 This allows you to keep the function to change the check boxes simple. Simply loop through all the elements in the first form found in the page. If the element type is not checkbox, continue the loop without executing the rest of it. If the element is a check box, determine whether action is read more..

  • Page - 236

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 233 Radio Buttons Radio buttons are called that because they look like the dials on old radios, in case you wondered. They act like check boxes, with the difference being that they belong to one group with the same name, and the user can choose only one. Radio buttons are very easy to use for read more..

  • Page - 237

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 234 The demo HTML includes some buttons to show the output of the JavaScript; you can test it out by opening it in a browser. The script shows how you can deal with radio buttons: formRadioGroup.js function setChoice(n) { var f = document.forms[0]; f.character[n].checked = true; } function read more..

  • Page - 238

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 235 Reading the currently selected choice is just as easy: you select the first form, store the characters list in a new variable called choices, and loop through it. Then you test the checked property of each of the elements in the array and break the loop when you find one that returns true. read more..

  • Page - 239

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 236 All you need to do to achieve this functionality is assign an event handler to the window that calls an init() function and another one that calls a change() function when the form is submitted. This function loops through all the form elements (after retrieving the form via getTarget()) and read more..

  • Page - 240

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 237 There are two kinds of select boxes: single-choice select boxes that allow one exclusive choice, and multiple-choice select boxes that allow the user to choose more than one option by holding down Ctrl and highlighting the options desired. Note ■ multiple-choice select read more..

  • Page - 241

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 238 if(selectBox.options[i].selected == 1) { choices.push(selectBox.options[i].text); } } alert(choices.join(', ')); } You can reach the select box via its name in the elements collection and create a new array called choices. (The [] is a shortcut notation for new read more..

  • Page - 242

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 239 Removing and Replacing Options in a Select Box You can remove an option by setting it equal to null: exampleSelectChoice.js (excerpt) function removeOption(fieldName,i) { var f = document.forms[0]; var selectBox = f.elements[fieldName]; selectBox.options[i] = null; } Replacing options is just as easy; read more..

  • Page - 243

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 240 exampleSelectChoice.js (continued) old.length++; for(i = 0; i < old.length; i++) { if(i == n) { old[i] = extraOption; Otherwise, you set the option to the old option and increase the j counter variable. Notice you need a second counter here because you cannot change the variable i during read more..

  • Page - 244

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 241 exampleDynamicForm.html (excerpt) <form method="post" action="send.php"> [... code snipped ...] <p><label for="subject">Subject</label> <select id="subject" name="subject"> <option value="generalEnquiry" selected="selected">General read more..

  • Page - 245

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 242 You define a class to apply to the elements you want to hide and the IDs of the two dynamic elements as properties of a main object called df. dynamicForm.js df = { hideClass : 'hide', letterOption : 'newsletter', subjectOption : 'subject', The init() method checks for DOM support read more..

  • Page - 246

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 243 dynamicForm.js (continued) subjectChange : function(e) { var t = DOMhelp.getTarget(e); var action = t.selectedIndex == 5 ? 'remove' : 'add'; DOMhelp.cssjs(action, df.subjectOpt, df.hideClass); if(action == 'remove') { df.subjectOpt.getElementsByTagName('input')[0].focus(); read more..

  • Page - 247

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 244 init : function() { if(!document.getElementById || !document.createTextNode){ return; } df.news = document.getElementById(df.letterOption); df.subject = document.getElementById(df.subjectOption); if(!df.subject || !df.news){ return; } df.newsOpt = read more..

  • Page - 248

    ChapTer 7 ■ JavaSCrIpT and USer InTeraCTIon: navIgaTIon and FormS 245 Summary of Forms and JavaScript I hope this chapter gave you insight as to what is possible with forms and JavaScript. You learned about the different properties and methods of forms themselves and each of the elements that they might contain with their individual properties and methods. You saw in read more..

  • Page - 249

    247 Chapter 8 Back-End Interaction with Ajax and Node.js You finally reached the chapter where I talk about Ajax. The good news is you can use Ajax to create really nice, slick interfaces, and you can extend JavaScript’s reach much further than the browser and the currently displayed document. The not-so-good news is that Ajax depends on the XMLHTTPRequest object (or XHR read more..

  • Page - 250

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 248 Tip ■ In addition to reading the official help FAQs at http://www.apachefriends.org/en/faq-xampp.html, Mac users can use MAMP, which does the same thing. You can download MAMP at http://www.mamp.info. Household Cleaning Liquid, Football Club, or Flash Gordon’s Spacecraft: What Is Ajax? Ajax originally stood read more..

  • Page - 251

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 249 At first glance, this appears to add an extra layer of complexity to the whole matter. However, the really cool thing about it is that the communication between the Ajax engine and the browser is triggered via JavaScript and not via page reloads. In practical terms, the end user spends less time waiting for read more..

  • Page - 252

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 250 Note ■ These links are not totally unobtrusive and up to the standard of the rest of the code examples in this book, but at least they work without javascript—the browser will simply show the text files when scripting is not available. It is very tempting, especially when using out-of-the-box Ajax read more..

  • Page - 253

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 251 The first step is to call the open() method to start the connection with the server and retrieve or send data. The open() method takes five parameters, three of which are optional: request = open(requestMethod, url[, sync, [name, [password]]]); The • requestMethod parameter (among some other options beyond the read more..

  • Page - 254

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 252 Once the request is initialized (readyState equals 1), it is a very good idea to give the user some feedback that there are things happening in the background. In this example, the script displays a “loading...” mess age inside the HTML output element, as shown in Figure 8-3. The other states cannot be read more..

  • Page - 255

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 253 The send() method sends your request to the server and can take request parameters to send to the server-side script being invoked. If you don’t have any parameters to send, it is safest to set it to null. (Internet Explorer accepts send() without any parameters, but this can cause problems in older read more..

  • Page - 256

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 254 This method enables you to obtain and use the data sent back from the XMLHttpRequest. The data can be read out in a few different formats based on responseType. Two text-based formats are responseText and responseXML. The difference between these is the type of output—responseText returns a string, and read more..

  • Page - 257

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 255 <id>2</id> <artist>Monty Python</artist> <title>The final Rip-Off</title> <comment>Double CD with all the songs</comment> </album> [... more albums snipped ...] </albums> You want to retrieve this data via XHR and display it as a table in read more..

  • Page - 258

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 256 request.onreadystatechange = function() { if(request.readyState == 1) { simplexhr.outputContainer.innerHTML = 'loading... '; } if(request.readyState == 4) { if( request.status && /200|304/.test( request.status ) ) { read more..

  • Page - 259

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 257 simpleXMLxhr.js (continued) var albums = data.getElementsByTagName('album'); for( i = 0 ; i < albums.length; i++ ) { For each album, you read the contents of the XML nodes by their tag name and retrieve their text content via firstChild.nodeValue. simpleXMLxhr.js (continued) tr = document.createElement('tr'); albumId = read more..

  • Page - 260

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 258 You can see that by doing the “right thing” in terms of DOM scripting, scripts can get rather convoluted. You could cut down the amount of code by using tool methods to create the table rows, but that means even more processing because the methods have to be called from within a loop. If you know read more..

  • Page - 261

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 259 Replacing XML with JSON Although XML is a popular method of data transfer formats—it is text based and you can ensure validity and systems being able to talk to each other via DTDs, XML Schemata, or RELAX NG. Ajax fans have become more and more aware that it can be quite a drag to convert XML to read more..

  • Page - 262

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 260 { "id" : "3", "artist" : "Ms Kittin", "title" : "I.com", "comment" : "Good electronica" } ] } The benefit is that the data is already in a format that JavaScript can understand. All you read more..

  • Page - 263

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 261 Note ■ This is a common myth about Ajax: it does not replace server-side code but is backed up by it and offers a slicker interface to it. XHR by itself can retrieve data only from the same server or send information to server-side scripts. You can’t, for example, access a database in read more..

  • Page - 264

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 262 exampleExternalRSS.html (excerpt) <p> <a href="http://rss.news.yahoo.com/rss/topstories" onclick="return readrss.doxhr('newsContainer',this.href)"> Get Yahoo news </a> </p> <div id="newsContainer"></div> Note ■ rss is an acronym for really simple syndication. read more..

  • Page - 265

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 263 request.send( null ); return false; }, The retrieved() function needs to change. First, it deletes the “loading . . .” message from the output container and retrieves the data in XML format using responseXML. Because the PHP script returns an error read more..

  • Page - 266

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 264 externalRSS.js (continued) readrss.outputContainer.innerHTML = '<ul>' + content + '</ul>'; return false; } The rest of the script remains unchanged; the failed() method displays an alert only when the XHR doesn’t succeed. externalRSS.js (continued) }, failed : function( requester ) { read more..

  • Page - 267

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 265 The differences in the script are that you need a property to define how long to wait before a timeout is triggered, one to store the window.timeout, and a Boolean property that defines whether there was a timeout or not. The Boolean has to be inside the doxhr() method because it needs to get initialized read more..

  • Page - 268

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 266 XHRtimeout.js (continued) if( request.readyState == 4 && !readrss.timedout ) { window.clearTimeout( readrss.toolong ); if( /200|304/.test( request.status ) ) { readrss.retrieved( request ); } else { readrss.failed( request ); } } read more..

  • Page - 269

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 267 The main page features the form with a DIV with an id you can use for the XHR output. exampleSelectBoxes.php (excerpt) <form action="exampleSelectBoxes.php" method="post"> <div id="formOutput"> <?php include('selectBoxes.php');?> </div> <p class="submit"><input read more..

  • Page - 270

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 268 The PHP script returns an HTML interface you can hook into at each stage of the process: If there hasn’t been any form data sent yet, it displays one select box with the ID • airport listing all the airports in the dataset. If there was an airport chosen and sent to the server, the script displays read more..

  • Page - 271

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 269 The init() method tests whether the W3C DOM is supported, retrieves the first form, and stores the Submit button with the ID select in a property—this is necessary to remove the button on the last step. It then creates a new paragraph and applies the class for the Ajax trigger defined earlier. read more..

  • Page - 272

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 270 var airportValue, destinationValue; dynSelect.outputContainer = document.getElementById(dynSelect.containerID ); if( !dynSelect.outputContainer ){ return; } Here is the XHR code, which defines the correct object and sets the onreadystatechange event listener. selectBoxes.js (continued) var request; try { request = new read more..

  • Page - 273

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 271 Because the form is sent using POST and not GET, you need to define the request a bit differently. First of all, you need to assemble the request parameters as a string. (This is the trail of variables on the URI when the send method is GET—for example, read more..

  • Page - 274

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 272 The retrieved() method doesn’t differ much from the other examples. Undo what you did in the previous step by changing the Submit button’s value back to Select before retrieving the responseText of the request and replacing the old form elements with the new ones. Add ?ajax to the href of the read more..

  • Page - 275

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 273 Created by Ryan Dahl with the goal of making a web application like Gmail, Node is an open source project that can run in multiple environments and can be hosted by companies like Heroku, Amazon’s AWS, Nodejitsu, and Joynet, which is also a sponsor of the project. Most famously LinkedIn uses Node for read more..

  • Page - 276

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 274 function startUp(){ function onRequest(request, response){ response.writeHead(200,{"Content-Type": "text/plain"}); response.end("It's the information age!"); } http.createServer(onRequest).listen(8080); } exports.startup = startUp; Now let’s make an index.js file to start it read more..

  • Page - 277

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 275 host: 'www.apress.com', path: '/9781430250920' }; callback = function(response) { var str = '' response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { console.log(str); read more..

  • Page - 278

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 276 Figure 8-9. Chrome Debugger used to debug Node.js applications Figure 8-10. JetBrain’s IntelliJIdea with Node.js editing and debugging features i read more..

  • Page - 279

    CHAPTer 8 ■ BACk-end InTerACTIon wITH AjAx And node.js 277 Summary I hope this has given you an insight into what can be done with JavaScript and XMLHttpRequest to create dynamic connections between the back end and the browser without reloading the page. Also, I hope this chapter helped you understand how you can take your JavaScript skill to the server side with read more..

  • Page - 280

    279 Chapter 9 Data Validation Techniques In this chapter, you will learn about using JavaScript to validate data entered by the user or coming from other systems. You already heard a lot about this in Chapter 2, which dealt with decisions involving data, and we will use some of that knowledge and extend it here. Data validation has gone read more..

  • Page - 281

    Chapter 9 ■ Data ValiDation teChniques 280 A Quick Reminder About Protecting Content with JavaScript Validation is one thing, protecting content with a password or obfuscating it via encryption is another. If you look around the web, you will find a lot of examples that promise that you can protect a web page from being available with a JavaScript password. Normally, these read more..

  • Page - 282

    Chapter 9 ■ Data ValiDation teChniques 281 administrators, you’ll be amazed how often they can replace a 50-line switch/case or if/else construct you wrote in JavaScript with a single regular expression. Many editing environments also feature “find” and “search and replace” functionality, allowing the use of regular expressions. Regular expressions are the cat’s pajamas read more..

  • Page - 283

    Chapter 9 ■ Data ValiDation teChniques 282 Wildcard Searches, Constraining Scope, and Alternatives The period character (.) plays the role of the joker card in regular expressions; it stands for “any character.” (This can be confusing, because in advanced web searches or on the DOS and UNIX command line, it is the asterisk, *.) var searchTerm = /c.t/gim; var searchTerm read more..

  • Page - 284

    Chapter 9 ■ Data ValiDation teChniques 283 Note ■ adding the question mark (?) after each of these means that the regular expression should match them but as few times as possible. For example, if you want to match the syntax of a serial number that consists of two groups of four characters, each separated with dashes, you use var searchTerm = read more..

  • Page - 285

    Chapter 9 ■ Data ValiDation teChniques 284 For example, if you want to test for a US Social Security number, which is a nine-digit number with dashes following the third and the fifth digits (for example, 456-33-1234), you can use the following regular expression, with optional dashes (using the ? quantifier), because the user might not enter them: var searchTerm = read more..

  • Page - 286

    Chapter 9 ■ Data ValiDation teChniques 285 The Power of Parentheses Grouping You might remember that to group an expression, you use parentheses, (). This not only groups the pattern, but also stores the results in special variables you can use later on. This is especially handy when you use it in conjunction with the replace() method. The results are stored in read more..

  • Page - 287

    Chapter 9 ■ Data ValiDation teChniques 286 There are many online resources that list patterns according to their task: The Regular Expression Library ( • http://regexlib.com/) has a searchable database of patterns. At Regular-Expressions.info ( • http://www.regular-expressions.info/), you’ll find a very extensive tutorial on regular expressions. RegEx Advice ( • http://regexadvice.com/) has read more..

  • Page - 288

    Chapter 9 ■ Data ValiDation teChniques 287 Safari 5, Firefox 16, Chrome 23, and Opera 21.1 support this. One of the nice things about constraint validation is that the browser will do the validation for you, displaying a warning when the field is empty. The input tag has the required attribute: <input type="text" id="firstName" required title="First Name is read more..

  • Page - 289

    Chapter 9 ■ Data ValiDation teChniques 288 Here is an example of the email input type: <input type="email" placeholder="Enter Email Address"> The Novalidate Attribute In the case that you want to disable the validation of a node on submission, use the following: <form novalidate> <input type="text" required > read more..

  • Page - 290

    Chapter 9 ■ Data ValiDation teChniques 289 <label>Message <textarea id="message"></textarea> </label> <button>Submit</button> In the preceding example, you can see :required and :optional have been added to CSS. In the first instance, you are making sure that any input tag that has the required attribute receives the style. In the next read more..

  • Page - 291

    Chapter 9 ■ Data ValiDation teChniques 290 In addition to the CSS classes used in the last two examples, some other classes are available: • in-range • out-of-range • read-only • read-write Detecting Support for HTML5 Form Attributes Not all browsers support every new input type. Browsers that don’t do so will ignore the type you give it and act as if the type is read more..

  • Page - 292

    Chapter 9 ■ Data ValiDation teChniques 291 form.addEventListener("submit", function(event){ if(email1.validity.valid && email2.validity.valid && email1.value && email2.value){ resultDiv.innerHTML = "<p>Email is valid and they match</p>"; }else{ read more..

  • Page - 293

    Chapter 9 ■ Data ValiDation teChniques 292 checkInputs(); event.preventDefault(); }, false); } function checkInputs(){ var resultDiv = document.getElementById("result"); resultDiv.hidden = true; var inputs = read more..

  • Page - 294

    Chapter 9 ■ Data ValiDation teChniques 293 Adding autocomplete functionality to your site is made easy with HTML5. First I will go over how it works and then create a JavaScript version that could be updated to pull data from a server. autoComplete.html (excerpts) <input type="text" name="srch" id="srch" list="datalist1"> <datalist read more..

  • Page - 295

    Chapter 9 ■ Data ValiDation teChniques 294 dynamicAutoComplete.html (excerpts) <script> function createDataList(){ var nameArray = new Array(); nameArray[0] = "Bill Gates"; nameArray[1] = "Linus Torvalds"; nameArray[2] = "Douglas Coupland"; nameArray[3] = read more..

  • Page - 296

    Chapter 9 ■ Data ValiDation teChniques 295 <script>jQuery.webshims.polyfill('forms');</script> <form> <input type="text" requred> <input type="submit" value="submit"> </form> Summary I hope you feel quite confident writing regular expressions and using constraint validation. HTML5 relieves you of having to write complex scripts to read more..

  • Page - 297

    297 Chapter 10 Modern JavaScript Case Study: A Dynamic Gallery In this chapter, you will learn how to develop a JavaScript-enhanced thumbnail gallery backed up by a PHP script. You’ll start with learning techniques related to static galleries and how to enhance them. Then you’ll move on to a gallery that uses PHP and Ajax to pull images dynamically from the server. read more..

  • Page - 298

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 298 If you want to offer thumbnail galleries in their original sense, you need to generate smaller thumbnail pictures of the large images you want to show. You can do that either as a batch process before you upload the gallery or on the fly via scripting on the read more..

  • Page - 299

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 299 Tip ■ You might as well use tables or definition lists for thumbnail galleries, as tables degrade better because they remain multicolumn constructs even in non-CSS browsers and definition lists are semantically correct, too. For the examples in this chapter, i used read more..

  • Page - 300

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 300 A method to show the picture • A method to set the picture to be shown • A method to navigate to the next or previous picture • The method setting the picture to be shown, setPic(), is necessary because both the showing method, showPic(), and the navigation method, navPic(), change the image in read more..

  • Page - 301

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 301 You start the createContainer() method by creating a new DIV element, storing it in a property called c, and assigning the large image container ID to it. fakeDynamic.js (continued) var p = document.createElement('p'); var cl = DOMhelp.createLink('#', fakegal.closeLabel); cl.className = fakegal.closeClass; read more..

  • Page - 302

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 302 fakeDynamic.js (continued) showPic : function(e) { var t = DOMhelp.getTarget(e); if(t.nodeName.toLowerCase() != 'a') { t = t.parentNode; } fakegal.current = t.i; var largePic = t.getAttribute('href'); fakegal.setPic(largePic); DOMhelp.cancelClick(e); }, In the event listener method showPic(), read more..

  • Page - 303

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 303 fakeDynamic.js (continued) a = fakegal.current == 0 ? 'add' : 'remove'; DOMhelp.cssjs(a, fakegal.prev, fakegal.hideClass); a = fakegal.current == fakegal.all-1 ? 'add' : 'remove'; DOMhelp.cssjs(a, fakegal.next, fakegal.hideClass); }, Test to see whether the current property of the main object is equal read more..

  • Page - 304

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 304 Displaying Captions Thumbnail galleries are visual constructs, but it is still a good idea to think about alternative text and image captioning. Not only will these make your gallery accessible to blind users, but they also allow for searching the thumbnail data and indexing it through search engines. Many read more..

  • Page - 305

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 305 exampleFakeDynamicAlt.html (excerpt) <ul id="thumbs"> <li> <a href="galleries/animals/dog2.jpg"> <img src="galleries/animals/tn_dog2.jpg" title="This square is mine" alt="Dog in a shady square"> </a> </li> <li> <a read more..

  • Page - 306

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 306 thumbsLinks[i].onclick = DOMhelp.safariClickFix; thumbsLinks[i].i = i; } fakegal.createContainer(); }, showPic : function(e) { var t = DOMhelp.getTarget(e); if(t.nodeName.toLowerCase() != 'a') { t = t.parentNode; } fakegal.current = t.i; var largePic = read more..

  • Page - 307

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 307 fakeDynamicAlt.js (continued) navPic : function(e) { var t = DOMhelp.getTarget(e); if(t.nodeName.toLowerCase() != 'a') { t = t.parentNode; } var c = fakegal.current; if(t == fakegal.prev) { c -= 1; } else { C += 1; } fakegal.current = c; var read more..

  • Page - 308

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 308 fakegal.prev = DOMhelp.createLink('#', ' '); fakegal.prev.innerHTML = fakegal.prevContent; fakegal.prev.className = fakegal.prevClass; DOMhelp.addEvent(fakegal.prev, 'click', fakegal.navPic, false); fakegal.prev.onclick = DOMhelp.safariClickFix; fakegal.c.appendChild(fakegal.prev); fakegal.caption = read more..

  • Page - 309

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 309 Figure 10-2. A dynamic PHP-driven thumbnail gallery example with thumbnail pagination and previous and next image preview on the large picture page This gallery is fully functional and accessible without JavaScript, but you might not want to reload the whole page every time the user clicks a read more..

  • Page - 310

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 310 You use this output to overwrite the HTML output of the original PHP script as shown in the demo examplePHPXHRgallery.php. Without JavaScript, it does the same as examplePHPgallery.php; however, when JavaScript is available, it will not reload the whole document, but only refresh read more..

  • Page - 311

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 311 dyngal_xhr.js (continued) load : function(e) { var t = DOMhelp.getTarget(e); if(t.nodeName.toLowerCase() != 'a') { t = t.parentNode; } var h = t.getAttribute('href'); h = h.replace(dyngal.originalPHP, dyngal.dynamicPHP); dyngal.doxhr(h, dyngal.contentID); DOMhelp.cancelClick(e); }, In the read more..

  • Page - 312

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 312 failed : function(request) { alert('The XMLHttpRequest failed. Status: ' + requester.status); return true; } } DOMhelp.addEvent(window, 'load', dyngal.init, false); The XHR methods are the same as those you used in Chapter 8. The only difference is that you need to call the read more..

  • Page - 313

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 313 When creating scripts like these, it is a good idea to keep the HTML as easy as possible. The less you expect from the maintainer, the more likely it is that people will use your script. In this case, all the maintainer needs to do to add a badge gallery to the HTML document is add an read more..

  • Page - 314

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 314 badge.php <?php $c = preg_match('/\d+/', $_GET['c']) ? $_GET['c'] : 5; $s = preg_match('/\d+/', $_GET['s']) ? $_GET['s'] : 0; $cd = is_dir($_GET['cd']) ? $_GET['cd'] : ' '; You define three variables: $c, which stores the number of thumbnails to be shown; $s, which is the index of what is currently read more..

  • Page - 315

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 315 Loop through the images and display an IMG element inside a link pointing to the large image for each array item. You can retrieve the link to the large image by removing the tn_ string of the array element’s value with str_replace(). badge.php (continued) if(($c+$s) <= sizeof($images)) { read more..

  • Page - 316

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 316 badge.doxhr('badge.php?cd=' + dir, newUL); parent.parentNode.insertBefore(newUL, parent); parent.parentNode.removeChild(parent); i--; } You create a new list element and add the badge class to it. You retrieve the link’s href attribute, read the window location, and remove anything in the read more..

  • Page - 317

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 317 retrieved : function(request, container) { var data = request.responseText; container.innerHTML = data; badge.assignHandlers(container); }, failed : function(requester) { alert('The XMLHttpRequest failed. Status: ' + requester.status); return true; }, The Ajax/XHR methods remain largely unchanged, the only read more..

  • Page - 318

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 318 badge.js (continued) show : function(e) { var t = DOMhelp.getTarget(e); if(t.nodeName.toLowerCase() != 'a') { t = t.parentNode; } var y = 0; if(self.pageYOffset) { y = self.pageYOffset; } else if (document.documentElement && document.documentElement.scrollTop) { y read more..

  • Page - 319

    CHaPter 10 ■ Modern JavaSCriPt CaSe StudY: a dYnaMiC GallerY 319 badge.js (continued) deletePic : function() { badge.container.innerHTML = ' '; } } DOMhelp.addEvent(window, 'load', badge.init, false); All the deletePic method needs to do is to set the innerHTML property of the container element to an empty string, thus removing the large image. Summary read more..

  • Page - 320

    321 Chapter 11 Using Third-Party JavaScript As you probably gathered by now, when you create a JavaScript application, you don’t need to reinvent the wheel and recode all the functionality from scratch every time—JavaScript has many, many functions available for you to use, and you can create your own reusable functions and objects, too. But it goes even further than read more..

  • Page - 321

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 322 One example of a REST API is from Twitter (details can be found at (https://dev.twitter.com/), which allows you to put together a URL to search for tweets by a certain user. The results are returned in the JSON format. In this example, %40 is the URL endoded code for the @ symbol: read more..

  • Page - 322

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 323 jQuery (http://jquery.com/) comprises a single JavaScript file, weighing in at only 32K, which you add to the head of your documents. It provides you with an amazing amount of utility methods to achieve web-specific tasks. The code you have to write to work with jQuery is very confusing to JavaScript beginners or developers who read more..

  • Page - 323

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 324 [... code example ...] </code></pre> <p>The CSS</p> <pre><code> [... code example ...] </code></pre> Let’s now write a script in jQuery that generates links preceding the code examples that allow for expanding and collapsing the examples instead of simply showing them, as demonstrated in read more..

  • Page - 324

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 325 As you can see, the code is amazingly short, but it’s also rather complex in terms of syntax. Let’s go through the example bit by bit so that you can understand what is going on: jqueryTest.js (excerpt) $(document).ready ( function() { The $(document).ready () method is an event handler that calls the function read more..

  • Page - 325

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 326 jqueryTest.js (continued) function() { $(this.parentNode.nextSibling).slideUp('slow'); $(this).html('Show Code'); } ) } ) The other case of toggle() in this example uses slideUp() to slowly hide the code example and changes the text of the link back to read more..

  • Page - 326

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 327 code=code.replace(/ /g,'&nbsp;'); o.nextSibling.innerHTML='<code>'+code+'</code>'; o.nextSibling.hascode=true; } ); } $(o.nextSibling).show(); } } ) Let’s read more..

  • Page - 327

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 328 You use toggle() to show and hide the code examples; however, unlike what you did with the last script, you store the original text of the link in a property called old when you show the code and replace the link text with “Hide Code”. You then invoke the function parseCode() with the link as a parameter when read more..

  • Page - 328

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 329 Dangers of jQuery and Other Libraries Using Their Own Syntax It is amazing how many day-to-day web-application and web-development tasks you can perform easily and quickly with jQuery. However, if you handed this document over to a third-party developer for maintenance, she’d have to know about jQuery or she would be completely read more..

  • Page - 329

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 330 exampleGoogleMaps.html (excerpt) <div id="map_canvas" style="width:100%; height:100%"> <p>Here you should see an interactive map, but you either have scripting disabled or your browser is not supported by Google Maps.</p> </div> The sample CSS code that Google provides will make your map full screen. read more..

  • Page - 330

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 331 Finally, the map object is created. When creating a map instance, you need to specify a div element in your HTML document that will contain the map. In addition, you pass the mapOptions object that contains the parameters to customize the map. The code in the above example should give you a map of Sitama Prefecture, read more..

  • Page - 331

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 332 The map is working, but with the current view it is hard to tell exactly what you should be paying attention to. To fix this, you need to add a marker. Creating a marker is similar to creating the map. You create a marker object and, in the constructor, add an object literal that has all the properties you want read more..

  • Page - 332

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 333 You also can use the API to display windows that will appear when the marker is clicked on. This can help to provide necessary information to the user in addition to links to related sites. In this example, you create a variable called contentString. Inside this variable, you add a string of HTML-formatted text. This will read more..

  • Page - 333

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 334 var marker = new google.maps.Marker({ position: myLatlng, animation: google.maps.Animation.DROP, map: map }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); } document.addEventListener("DOMContentLoaded", loadMapAPI, false); The last feature you will add is the ability to read more..

  • Page - 334

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 335 Full Service: Introducing Twitter Bootstrap Early in the chapter, you took at look at part of Twitter’s REST API. In addition to the REST API, which provides access to its data, Twitter has released Twitter Bootstrap (found at http://twitter.github.com/bootstrap/). Bootstrap is a free collection of tools for creating both web read more..

  • Page - 335

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 336 These files can be copied into your site and referenced in your HTML documents. To get started, use the following code: exampleBootstrapTemplate.html <!doctype html> <html> <head> <title>Bootstrap Template</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link read more..

  • Page - 336

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 337 Now that you know bootstrap is working, you can use some of its features. First you can put the header inside a div that uses the container class. Next you can add a paragraph declaring that what comes next is your button. Inside this paragraph, you use the text-info class to give it style. After that, you can add read more..

  • Page - 337

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 338 With the button in place, you can now turn it into a drop-down menu. Because you downloaded the default bootstrap .zip file, you don’t need to download the drop-down plugin. The plugins for Bootstrap are made to work with jQuery, and because you also added that to your document, this should work by only adding the read more..

  • Page - 338

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 339 <div class="modal-body"> <p>The body of the window</p> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> <button read more..

  • Page - 339

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 340 $('#header1').click(function(){ $('#collapseOne').collapse('toggle'); }); $('#header2').click(function(){ $('#collapseTwo').collapse('toggle'); }); }); Here you turn off the data API. Then you assign click events to two HTML elements, called header1 and read more..

  • Page - 340

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 341 exampleBootstrapCarousel.html (excerpt) <a class="carousel-control left" href="#myCarousel" data-slide="prev">&lsaquo;</a> <a class="carousel-control right" href="#myCarousel" data-slide="next">&rsaquo;</a> In the HTML document, this attribute is associated with the anchor tags that are being used to read more..

  • Page - 341

    ChAPter 11 ■ UsIng thIrD-PArty JAvAsCrIPt 342 Summary This chapter has given you a taste of some of the services aviaible to you at the moment, and I am sure that this is simply the beginning of a longer experience you’ll have with using shared content, information, and services. Many developers spend a lot of time creating wonderful code just to realize that there read more..

  • Page - 342

    343 APPENDIX A Debugging JavaScript In this appendix, I will introduce you to some tricks and tools to debug your JavaScript code. It is very important to get acquainted with debugging tools, because programming consists to a large extent of trying to find out what went wrong a particular time. Some browsers help you with this problem; others make it harder by having their read more..

  • Page - 343

    APPENDIX A ■ DEbuggINg JAvAScrIPt 344 Trying to Access Undefined Variables I talked about it in the second chapter of the book: you define variables either by declaring them with or without an additional var keyword. (The latter is necessary to define the scope of the variable.) Keep in mind that strict mode will prevent you from implicitly declaring variables (variables read more..

  • Page - 344

    APPENDIX A ■ DEbuggINg JAvAScrIPt 345 Chrome’s developer tools will tell you that there is an error in line 23—“ ‘o utputID’ is not defined,” as shown in Figure A-1. Figure A-1. Chrome showing an error on line 23 Figure A-2. The code shown with a highlight on line 23 However, if you look at the code in line 23 as shown in Figure A-2, nothing read more..

  • Page - 345

    APPENDIX A ■ DEbuggINg JAvAScrIPt 346 Typos in parameters are a very confusing bug, because browsers tell you the error occurred in the line where the variable is used and not where you made the mistake. Incorrect Number of Closing Braces and Parentheses Another common mistake is not closing curly braces or keeping an orphaned closing brace in the code when deleting some read more..

  • Page - 346

    APPENDIX A ■ DEbuggINg JAvAScrIPt 347 case 'Flintstone': father = "Fred"; mother = "Wilma"; child = "Pebbles"; break; } var out = document.getElementById( outputID ); var newUL = document.createElement( 'ul' ); newUL.appendChild( makeListElement( father ) ); newUL.appendChild( makeListElement( read more..

  • Page - 347

    APPENDIX A ■ DEbuggINg JAvAScrIPt 348 if( x == end ) { alert(x + ' is the end of the range'); } if( x != start && x != end ) { alert(x + ' is in the range'); } } else { alert( x + ' is not in the range' ); } } The previously missing curly brace is shown in bold read more..

  • Page - 348

    APPENDIX A ■ DEbuggINg JAvAScrIPt 349 Concatenation Gone Wrong Concatenation is happening a lot when you use JavaScript to output HTML. Make sure that you don’t forget the plus (+) signs in between the different parts to concatenate to a whole: father = "Peter"; mother = "Lois"; child = "Chris"; family = father+" "+mother+" "child; read more..

  • Page - 349

    APPENDIX A ■ DEbuggINg JAvAScrIPt 350 Assigning Instead of Testing the Value of a Variable When testing the value of a variable, it is all too easy to assign it instead of testing it: all you need to do is forget an equal sign: if(Stewie = "talking") { Brian.hear(); } This code entices Brian to hear all the time, not only when Stewie has something read more..

  • Page - 350

    APPENDIX A ■ DEbuggINg JAvAScrIPt 351 exampleDebugTest.html (excerpt) <script type="text/javascript" src="../DOMhelp.js"></script> <script type="text/javascript"> function DOMDebugTest(){ DOMhelp.initDebug(); for(var i = 0; i < 300; i++ ) { DOMhelp.setDebug( i + ' : ' + ( i % 3 == 0 ) + '\n' ); } } read more..

  • Page - 351

    APPENDIX A ■ DEbuggINg JAvAScrIPt 352 Sequential Uncommenting Another easy way to trace an error is to comment out the whole script and uncomment it function by function or—if it is a single function—line by line. Test the script every time you uncomment a line by reloading it in a browser, and you will quickly get to the one that causes the error. This can take read more..

  • Page - 352

    APPENDIX A ■ DEbuggINg JAvAScrIPt 353 This enables the Develop drop-down menu. Some of the features available allow you to do things like quickly turn off JavaScript or change the user agent to test what your page would look like using another browser. (See Figure A-5.) Safari also has developer tools. By selecting Develop, Show Web Inspector, you can turn on the read more..

  • Page - 353

    APPENDIX A ■ DEbuggINg JAvAScrIPt 354 Chrome Chrome has its tools under View, Developer, Developer Tools. (See Figure A-8.) Figure A-8. Showing the developer tools in Chrome Figure A-7. Showing the JavaScript console in Firefox Inspecting and Debugging Your Code In all of these browsers, you have the ability to dig in and look at the code. When trying to single something read more..

  • Page - 354

    APPENDIX A ■ DEbuggINg JAvAScrIPt 355 The same is true for CSS. By using the Styles panel on the right side (as shown in Figure A-10), you can turn off, edit, or add CSS directly in the browser and see the results instantly. Figure A-9. Editing HTML directly in Chrome Figure A-10. Editing CSS directly in Chrome using the Styles panel read more..

  • Page - 355

    APPENDIX A ■ DEbuggINg JAvAScrIPt 356 As these changes are being made, you are updating only the code that is currently loaded in your browser. The original code in your editor is not being updated. To override that code, you can save (control/command–S) and override the original files with your updated ones. Because the focus of this book is on JavaScript, let’s read more..

  • Page - 356

    APPENDIX A ■ DEbuggINg JAvAScrIPt 357 From the console, you have access to all the JavaScript code that is in your document. Every object that is built into the browser and every object that you wrote in your code are available and can be executed from the console. For example, using one of the files from Chapter 5, suppose I wrote the following: sc.init The read more..

  • Page - 357

    APPENDIX A ■ DEbuggINg JAvAScrIPt 358 As you write JavaScript, there is one command you might use more than any other to make sure that things are working the way you think they should: console.log(); You used this in the try/catch example. If you have the console open, you can see the results of those statements printed in the console. In other languages, this read more..

  • Page - 358

    APPENDIX A ■ DEbuggINg JAvAScrIPt 359 If you come from a back-end coding environment, you might have already used or at least heard about unit testing(http://en.wikipedia.org/wiki/Unit_testing). In a nutshell, unit testing means that you write test cases for all your methods and functions, and you use a testing harness to run all these tests in succession when you press a read more..

  • Page - 359

    A „ „„„„„„„ „ Anonymous function, 67 B „ „„„„„„„ „ Back-end interaction, 247 Ajax, 248 external files, 249 open() method, 251 optional parameters, 251 outputContainer, 250 readyState property, 251 retrieved() method, 252 send() method, 253 sync parameter, 251 vsv. traditional requests, 248 user notification, 252 variable definition, 250 XMLHttpRequest failed, 253 callbacks, 274 debugging, 275 read more..

  • Page - 360

    string, 14 escape sequences, 15 variables, 18 prompt() function, 19 Data validation, 279 client-side validation, 279 constraint validation, 286 additional attributes, 287 API, 290 browser support, 290 CSS pseudo classes, 288 designating form elements, 287 erroneous fields, 291 nonvalidate attribute, 288 Polyfills, 294 Webshims, 294 content protection, 280 dynamic validation AJAX techniques, 293 Google, 292 read more..

  • Page - 361

    F „ „„„„„„„ „ Flash of unstyled content (FOUC), 143 Forms, 225 basics of, 226 elements, 227 blur() and focus(), 229 check boxes, 231 cols and rows attributes, 228 custom form elements, 244 disable elements, 243 globally supported properties, 229 hidden fields and password fields, 230 hide and show, 240 length, 227 methods, 228 properties, 228 push buttons, 235 radio buttons, 233 read more..

  • Page - 362

    window methods, 73 alert(), 73 confirm(), 76 nifty JavaScripts, 78 prompt(), 76 Windows (see Windows) N „ „ „ „„ „ Navigation, 199 basics of, 200 browser window.history object, 203 window.location object, 202 in-page navigation, 203 currentLink property, 206 init() method, 205 inner navigation, 205 panel interface, 207 replace() method, 206 sections and sectionLinks, 209 showSection() method, 206 read more..

  • Page - 363

    initialization method, 171 links, 173 new list, images, 172 parameter, 172 preview without JavaScript, 171 retreival of images, 173 thumbnails, 170 embedded, 161 array list, 166 CSS and HTML classes, 162 CSS class, 168 CSS vs. JavaScript, 164 initialization method, 163 links (forward and backward), 167 list replacement, 165 parameters, 165 photoListInlineSlides.js, 163 variable, 166 with JavaScript, read more..

  • Page - 364

    Windows, 149 and JavaScript, 174 addition of array, 186 animating intervals, 182 animations, 184 Boolea property, 175 cross site scripting (XSS), 175 CSS design, 191 desktop browsers, 177 document part, 175 DOM check, 191 DOM support, 193 dynamical document, 196 feedback mathods, 177 function calls, 181 HTML pop ups, 179 interaction, 180 labels(slide show), 186 Layer Ads, 190, 192 methods, read more..

  • Page - 365

    Beginning JavaScript with DOM Scripting and Ajax Second Edition Russ Ferguson Christian Heilmann read more..

  • Page - 366

    Beginning JavaScript with DOM Scripting and Ajax: Second Edition Copyright © 2013 b y Russ Ferguson, Christian Heilmann This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any read more..

  • Page - 367

    For Dad. Thanks for Saturdays full of cartoons, Doctor Who and Atari Basic —Russ Ferguson To Ioanna, who can sleep and look like an angel while some geek next to her hacks on the keyboard of a laptop and constantly mutters “Why won’t you work” under his breath. —Christian Heilmann read more..

  • Page - 368

    vii Contents About the Authors ��������������������������������������������������������������������������������������������������������������� xv About the Technical Reviewer read more..

  • Page - 369

    ■ Contents viii The Composite Data Types: Array and Object ������������������������������������������������������������������������������23 Objects JavaScript Supplies You with: String, Date, and Math read more..

  • Page - 370

    ■ Contents ix Accessing the Document via the DOM ����������������������������������������������������������������������������������������78 Of Children, Parents, Siblings, and Values read more..

  • Page - 371

    ■ Contents x Slide Shows ������������������������������������������������������������������������������������������������������������������������������������������������������� 160 read more..

  • Page - 372

    Download from Wow! eBook <www.wowebook.com> ■ Contents xi A Larger Ajax Example: Connected Select Boxes ���������������������������������������������������������������������������������������������� 266 Node�js read more..

  • Page - 373

    ■ Contents xii Chapter 10: Modern JavaScript Case Study: A Dynamic Gallery ■ �����������������������������������297 Basics of Thumbnail Galleries read more..

  • Page - 374

    ■ Contents xiii Built in Developer Tools �������������������������������������������������������������������������������������������������������������352 Microsoft Internet Explorer read more..

  • Page - 375

    xv About the Authors Russ Ferguson is a freelance developer and instructor in the New York City area. His interest in computers goes back to Atari Basic, CompuServe, and BBS systems in the mid 1980s. For over 10 years, he has been fortunate to teach at Pratt Institute, where subjects have been as diverse as the student body. Working in New York has given him read more..

  • Page - 376

    xvii About the Technical Reviewer Dr. Paddy Byers is an independent developer and consultant with a long-standing interest in web technology and the mobile web in particular. He has been prominent in a series of efforts to enable web applications to deliver the same functionality and experiences as native apps, including authoring the BONDI specification and participating in read more..

  • Page - 377

    xix Acknowledgments I want to thank everyone at Apress for the help in putting this together: Louise for giving me a chance to work on this, Anamika for keeping me on track, and Paddy for helping me explain everything better. I really appreciate it. I also need to thank my family for being supportive after a rough year and, more recently, dealing with me as I read more..

Write Your Review