Beginning JavaScript with DOM Scripting and Ajax

If you want to learn about JavaScript from scratch—what it is, what to use it for, and how to make it work with other technologies like CSS and HTML—you have picked up the right book.


Christian Heilmann


512 Pages

30830 Reads

55 Downloads

English

PDF Format

16.4 MB

Java Script

Download PDF format


  • Christian Heilmann    
  • 512 Pages   
  • 23 Feb 2015
  • Page - 1

    THE EXPERT’S VOICE ® IN WEB DEVELOPMENT Christian Heilmann Foreword by Simon Willison, Technology Development at Yahoo! Beginning JavaScript with DOM Scripting and Ajax From Novice to Professional The ultimate guide to modern JavaScript development! read more..

  • Page - 2

    Beginning JavaScript with DOM Scripting and Ajax From Novice to Professional ■■■ Christian Heilmann read more..

  • Page - 3

    Beginning JavaScript with DOM Scripting and Ajax: From Novice to Professional Copyright © 2006 by Christian Heilmann All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the read more..

  • Page - 4

    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. read more..

  • Page - 5

    read more..

  • Page - 6

    v Contents at a Glance Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . read more..

  • Page - 7

    read more..

  • Page - 8

    vii Contents Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . read more..

  • Page - 9

    viii ■CONTENTS Making Decisions in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 The Logical and Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . 45 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . read more..

  • Page - 10

    ■CONTENTS ix Creating, Removing, and Replacing Elements. . . . . . . . . . . . . . . . . . . . . . 109 Avoiding NOSCRIPT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Shortening Your Scripts via InnerHTML. . . . . . . . . . . . . . . . . . . . . . . 115 DOM read more..

  • Page - 11

    x ■CONTENTS ■CHAPTER 7 JavaScript and User Interaction: Navigation and Forms. . . 241 Navigation and JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 The Fear of the Page Reload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Basics read more..

  • Page - 12

    ■CONTENTS xi Basic JavaScript Validation with String and Numeric Methods . . . . . . . 346 String Validation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 Numeric Validation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352 Regular read more..

  • Page - 13

    xii ■CONTENTS ■CHAPTER 11 Using Third-Party JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 What the Web Offers You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 Code Snippets, RSS Feeds, APIs, and Libraries . . . . . . . . . . read more..

  • Page - 14

    xiii Foreword There has never been a more exciting time to learn JavaScript. It may be a cliché, but it’s certainly true. After years spent banished in a wilderness of browser wars and false promises, JavaScript has finally emerged as an essential part of any web developer’s toolbox. No longer just a vehicle for ads and annoyances, it is now a valuable component of read more..

  • Page - 15

    read more..

  • Page - 16

    xv About the Author ■CHRISTIAN HEILMANN grew up in Germany and, after a year working with people with disabilities for the Red Cross, spent a year as a radio producer. From 1997 onwards, he worked for several agencies in Munich as a web developer. In 2000, he moved to the US to work for eToys and, after the dot-com crash, he moved to the UK where he read more..

  • Page - 17

    read more..

  • Page - 18

    xvii About the Technical Reviewer ■JON STEPHENS has contributed to numerous books on web and open source technologies as an author, reviewer, and editor. He’s particu- larly keen on JavaScript, PHP, Linux, and MySQL. Jon coauthored Professional JavaScript, Second Edition (Wrox Press, 2001), Beginning MySQL Database Design and Optimization: From Novice to Profes- sional read more..

  • Page - 19

    read more..

  • Page - 20

    xix Acknowledgments I’d like to acknowledge all who helped in getting this book done—Chris, Beth, Ami, Katie, and Charles at Apress, and Jon Stephens. I learned a lot, especially that writing a book is much more work than I thought. I’d also like to thank those who helped me by solving problems and asking for more and more features—my fellow WaSP DOM read more..

  • Page - 21

    read more..

  • Page - 22

    xxi Introduction If you want to learn about JavaScript from scratch—what it is, what to use it for, and how to make it work with other technologies like CSS and HTML—you have picked up the right book. If you already have a considerable amount of experience with JavaScript, but want to bring your knowledge up to date, you have also picked up read more..

  • Page - 23

    xxii ■INTRODUCTION What This Book Will Cover JavaScript is probably simultaneously the most underrated and the most misused language in web development, but use it properly, and it can be a very valuable tool in your toolbox. In the following pages, we’ll look at the basics of JavaScript and modern JavaScript techniques, including DOM scripting for dynamic behavior and read more..

  • Page - 24

    ■INTRODUCTION xxiii But what happens when you get a problem? You have many options available to you. First, try getting ahold of me via my web site (http://wait-till-i.com) or mailing Apress about the issue (contact details available at http://www.apress.com). Second, try visiting any of the JavaScript forums available on the Web. Some of the best are • evolt’s thelist: read more..

  • Page - 25

    read more..

  • Page - 26

    1 ■ ■ ■ CHAPTER 1 Getting Started with JavaScript This book is about a scripting language called JavaScript and how to use it in a practical man- ner. 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 other JavaScripts. read more..

  • Page - 27

    2 CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT It is my credo that JavaScript has a place in modern web development, but we cannot take it for granted that the visitor will be able to use or even experience all the effects and functionality we can achieve with JavaScript. JavaScript allows us to completely change the web page by add- ing and removing or read more..

  • Page - 28

    CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT 3 In this chapter you’ll learn • What JavaScript is and what it can do for you • The advantages and disadvantages of JavaScript • How to add JavaScript to a web document and its essential syntax • Object-oriented programming (OOP) in relation to JavaScript • How to write and run a simple JavaScript read more..

  • Page - 29

    4 CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT Some information, such as calculations and verifying the information on a form, may not need to come from the server. JavaScript is executed by the user agent (normally a browser) on the visitor’s computer. We call this client-side code. This could result in fewer trips to the server and faster-running web sites. read more..

  • Page - 30

    CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT 5 Problems and Merits of JavaScript As I mentioned at the outset of this chapter, JavaScript has been an integral part of web devel- opment over the last few years, but it has also been used wrongly. As a result, it has gotten a bad reputation. The reason for this is gratuitous JavaScript effects, like moving page read more..

  • Page - 31

    6 CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT In many cases, you might want to have a server-side backup plan. It would test to see whether the user agent supports the functionality desired and, if it doesn’t, the server takes over. Independence of scripting languages is a legal requirement for web sites, defined in the Digital Discrimination Act for the UK, read more..

  • Page - 32

    CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT 7 • Lightweight environment: Instead of downloading a large file like a Java applet or a Flash movie, scripts are small in file size and get cached (held in memory) once they have been loaded. JavaScript also uses the browser controls for functionality rather than its own user interfaces like Flash or Java applets read more..

  • Page - 33

    8 CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT JavaScript Syntax Before we go any further, we should discuss some JavaScript syntax essentials: • // indicates that the rest of the current line is a comment and not code to be executed, so the interpreter doesn’t try to run it. Comments are a handy way of putting notes in the code to remind us read more..

  • Page - 34

    CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT 9 var myName = prompt ("Enter you r name",""); // 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 read more..

  • Page - 35

    10 CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT </head> <body> <h1>Test Page </h1> <script type="text/JavaScript"> alert( 'Second script Block' ); </script> <p>Some more HTML</p> <script type="text/JavaScript"> alert( 'Third script Block' ); function doSomething() { alert( 'Function in Third script Block' ); } read more..

  • Page - 36

    CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT 11 Although there’s another alert statement inside the function a few lines down, it doesn’t execute and display the message. This is because it’s inside a function definition (function doSomething()) and code inside a function executes only when the function is called. An Aside About Functions We’ll be talking read more..

  • Page - 37

    12 CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT Objects Objects are central to the way we use JavaScript. Objects in JavaScript are in many ways like objects in the world outside programming (it does exist, I just had a look). In the real world, an object is just a “thing” (many books about object-oriented pr ogramming compare objects to nouns): a car, a read more..

  • Page - 38

    CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT 13 ■Note There is some debate as to whether JavaScript is an object-based language or an object-oriented language. The difference is that an object-based language uses objects for doing programming but doesn’t allow the coder to use object-oriented programming in their code design. An object-oriented read more..

  • Page - 39

    14 CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT <script t ype="text/javascript"> // Define a variable called cssName and a message // called resolutionInfo var cssName; var resolutionInfo; // If the width of the screen is less than 650 pixels if( screen.availWidth < 650 read more..

  • Page - 40

    CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT 15 if ( screen.availWidth < 650 ) { // define the style Variable as the low-resolution style cssName = 'lowres.css'; resolutionInfo = 'low resolution'; } The code carries on checking the screen size using the else statement. The final else only occurs if neither of the other evaluations have resulted in code being read more..

  • Page - 41

    16 CH APTER 1 ■ GETTING STARTED WITH JAVASCRIPT Summary In this chapter, we’ve taken a look at what JavaScript is, how it works, and what its advantages and disadvantages are. I noted that the biggest disadvantage is that we cannot rely on it as a given. However, I also mentioned that using JavaScript can make web sites a nicer and slicker experience. read more..

  • Page - 42

    17 ■ ■ ■ 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 by read more..

  • Page - 43

    18 CH APTER 2 ■ D ATA AND DECISIONS Data, Data Types, and Data Operators Data is used to store information, and, in order to do that more effectively, JavaScript needs to have each piece of data assigned a type. This type stipulates what can or cannot be done with the data. For example, one of the JavaScript data types is number, which allows you to read more..

  • Page - 44

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 19 Both methods are fine, just as long as you close the string the same way you opened it and don’t try to delimit it like this: document.write( 'some characters" ); document.write( "some characters' ); Of course, you might want to use a single or double quotation mark inside the string itself, in read more..

  • Page - 45

    20 CH APTER 2 ■ D ATA AND DECISIONS Table 2-1. Common Escape Sequences Let’s amend this string, which causes a syntax error: document.write( 'Paul's characters' ); so that it uses the escape sequence (\') and is correctly interpreted: document.write( 'Paul\'s characters' ); The escape sequence tells the JavaScript interpreter that the single quotation mark belongs to read more..

  • Page - 46

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 21 Operators JavaScript has a number of operators that you can use to manipulate the data in your pro- grams; you’ll probably recognize them from math. Table 2-2 presents some of the most commonly used operators. Table 2-2. JavaScript Operators Here they are in use: <html> <body> <script t read more..

  • Page - 47

    22 CH APTER 2 ■ D ATA AND DECISIONS 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 calculation 1 + 2 * 3 is carried out like this: 2 * 3 = 6 6 + 1 = 7 All operators have an order of precedence. Multiplication, division, and modulus read more..

  • Page - 48

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 23 This is how the calculations for the preceding are performed: (1 + 1) = 2 (2 + 3) = 5 2 * 5 = 10 10 * 5 = 50 As we’ve seen, JavaScript’s addition operator adds the values. What it actually does with the two values depends on the data type that you’re using. For example, if you’re working read more..

  • Page - 49

    24 CH APTER 2 ■ D ATA AND DECISIONS We declare a variable by giving it a unique name and using the var keyword. Variable names have to start with a letter of the alphabet or with an underscore, while the rest of the name can be made up only of numbers, letters, the dollar sign ($), and underscore characters. Do not use any other characters. read more..

  • Page - 50

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 25 The prompt() function is a JavaScript function that asks the user to enter a value and then returns it to the code. Here we’re assigning the value entered to the variable eurosToConvert. Initializing your variables is a very good idea, especially if you can give them a default value that’s useful to the read more..

  • Page - 51

    26 CH APTER 2 ■ D ATA AND DECISIONS // Declare a new variable and use it to store the // number of euros var eurosToConvert = prompt( "How man y Euros do you wish ➥ to convert", "" ); // Declare a variable to hold the result of the euros // multiplied by the read more..

  • Page - 52

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 27 However, if we rewrite the code to allow the user to enter his own number using the prompt() function, then we’ll get a different calculation altogether: <html> <body> <script t ype="text/javascript"> var userEnteredNumber = prompt( "Please enter a number", ➥ "" read more..

  • Page - 53

    28 CH APTER 2 ■ D ATA AND DECISIONS document.write( typeof( userEnteredNumber ) ); </script> </body> </html> This will write string into the page. The way to ensure that the interpreter is using the desired number data type is to explicitly declare that the data is a number. There are three functions you can use to read more..

  • Page - 54

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 29 The data entered is read as a string in the first line. Then parseFloat() converts 23.50 from a string to a floating point number, and in the next line parseInt() strips out the fractional part (without rounding up or down). The variable is then converted to a number using the Number() function, stored read more..

  • Page - 55

    30 CH APTER 2 ■ D ATA AND DECISIONS This will not throw any error, but it does not help the visitor much, as the meaning of NaN is not common knowledge. Later on we will deal with conditions, and you’ll see how you could prevent an output that does not make much sense to the non-JavaScript-savvy user. And that’s all you need to know about read more..

  • Page - 56

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 31 Creating a String Object Let’s work with the implicit method first: we’ll begin declaring a new variable and assign it a new string primitive to initialize it. Try that now using typeof()to make sure that the data in the variable myStringPrimitive is a string primitive: <html> <body> read more..

  • Page - 57

    32 CH APTER 2 ■ D ATA AND DECISIONS So myStringPrimitive is still holding a string primitive after the temporary conversion. We can also create String objects explicitly, using the new keyword together with the String() constructor: <html> <body> <script t ype="text/javascript"> var myStringObject = new String( read more..

  • Page - 58

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 33 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 t ype="text/javascript"> var userEmail= prompt( "Please enter your email read more..

  • Page - 59

    34 CH APTER 2 ■ D ATA AND DECISIONS We’re extracting Homer from the string in the variable characterName, using indexOf() to find the start of the last name, and adding 9 to it to get the index of the start of the first name (as “Simpson, ” is 9 characters long), and storing it in firstNameIndex. This is used by the substring() method to read more..

  • Page - 60

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 35 Using the Date Object The Date object has a lot of methods that you can use to get or set a date or time. You can use local time (the time on your computer in your time zone) or UTC (Coordinated Universal Time, once called Greenwich Mean Time). While this can be very useful, you need to be read more..

  • Page - 61

    36 CH APTER 2 ■ D ATA AND DECISIONS This can be a handy feature if you need to add days onto a date. Usually we’d have to take into account the number of days in the different months, and whether it’s a leap year, if we wanted to add a number of days to a date, but it’s much easier to use JavaScript’s understand- ing of dates read more..

  • Page - 62

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 37 method. If you’re using IE5.5+ or Gecko-based browsers (Mozilla, Netscape >6), toDateString() produces a nicely formatted string using the date alone. You can use the same methods for get and set if you’re working with UTC time—all you need to do is add UTC to the method name. So getHours() becomes read more..

  • Page - 63

    38 CH APTER 2 ■ D ATA AND DECISIONS Here they are at work in a simple example: <html> <body> <script t ype="text/javascript"> var numberToRound = prompt( "Please enter a num ber", "" ) document.write( "round( ) = " + Math. round( numberToRound ) ); document.write( "<br>" read more..

  • Page - 64

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 39 0 and 5, so by adding 1, we can get a number between 1 and 6. This approach won’t give you a perfectly balanced die, but it’s good enough for most purposes. Here’s the code: <html> <body> <script t ype="text/javascript"> var diceThrow = Math.round( Math.random( ) read more..

  • Page - 65

    40 CH APTER 2 ■ D ATA AND DECISIONS Once we’ve populated an array, we can access its elements through their indexes or posi- tions (which, once again, are zero-based) using square brackets: <html> <body> <script t ype="text/javascript"> var preInitArray = new Array( "First Item", ➥ "Second Ite m", "Third read more..

  • Page - 66

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 41 anArray[itemIndex] = "Fruit"; anArray[itemKeyword] = 0.75; document.write( anArray[itemIndex] + "<br>" ); document.write( anArray[itemKeyword] ); </script> </body> </html> Let’s put what we’ve discussed about arrays and the Math object read more..

  • Page - 67

    42 CH APTER 2 ■ D ATA AND DECISIONS And that’s all there is to it. Having the banner change will make it more noticeable to visi- tors than if you displayed the same banner every time they came to the page—and, of course, it gives the impression that the site is being updated frequently. The Array Object’s Methods and Properties One of the read more..

  • Page - 68

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 43 The original array is unaffected, but you could overwrite the Array object in the variable by setting it to the result of the slice() method if you needed to: fullArray = fullArray.slice( 1, 4 ); Joining Two Arrays The Array object’s concat() method allows us to concatenate arrays. We can add two or more read more..

  • Page - 69

    44 CH APTER 2 ■ D ATA AND DECISIONS The resulting string, lineUp, has the value "John, Paul, George, Ringo". The opposite of join() is split(), which is a method that converts a string to an array. <script type="text/javascript"> var lineUp="John, Paul, George, Ringo"; var members=lineUp.split( ', ' ); alert( read more..

  • Page - 70

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 45 If you wanted to change the order the sorted elements are displayed, you can use the reverse() method to display the last in the alphabet as the first element: <script type="text/javascript"> var arrayToSort = new Array( "Cabbage", "Lemon", ➥ "Apple", "Pear", "Banana" ); read more..

  • Page - 71

    46 CH APTER 2 ■ D ATA AND DECISIONS Comparing Data Table 2-3 lists some of the more commonly used comparison operators. Table 2-3. Comparisons in JavaScript ■Caution Beware the == equality operator: it’s all too easy to create errors in a script by using the assign- ment operator, =, by mistake. These operators all work with string type data as well read more..

  • Page - 72

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 47 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 character of each string, then the second character, and so on. Uppercase A is represented in ASCII by the number read more..

  • Page - 73

    48 CH APTER 2 ■ D ATA AND DECISIONS You’ll get false returned. In fact, what we’ve done here is compare two String objects rather than the characters of two string primitives and, as the returned false indicates, two String objects can’t be the same object even if they do hold the same characters. If you do need to compare the strings held read more..

  • Page - 74

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 49 Conditional Statements The if...else structure is used to test conditions and looks like this: if ( condition ) { // Execute code in here if condition is true } else { // Execute code in here if condition is false } // After if/else code execution resumes here If the condition being tested is true, the code read more..

  • Page - 75

    50 CH APTER 2 ■ D ATA AND DECISIONS ■Note Remember to keep error messages as polite and helpful as possible. Good error messages that inform users clearly what is expected of them make using applications much more painless. We can create more complex conditions by using logical operators and nesting if statements: <html> <body> read more..

  • Page - 76

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 51 Try reading this code without the indenting or spacing: <html> <body> <script type="text/javascript"> // Ask for a number using the prompt() function and try to make it a number var userNumber = Number(prompt("Enter a num ber between 1 and 10","")); // If the value of userNumber is NaN, ask read more..

  • Page - 77

    52 CH APTER 2 ■ D ATA AND DECISIONS document.write( "The number you ent ered was " + ➥ userNumber ); } </script> </body> </html> The code does the same thing as the earlier piece, but uses an else if statement instead of a nested if, and is two lines shorter. Breaking Out of a Branch or Loop read more..

  • Page - 78

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 53 The values of the cases can be of any data type, numbers or strings, for example. We can have just one or as many cases as we need. Let’s look at a simple example: <html> <body> <script t ype="text/javascript"> // Store user entered number between 1 and 4 in read more..

  • Page - 79

    54 CH APTER 2 ■ D ATA AND DECISIONS You can use any valid expression inside the switch statement—a calculation, for example: switch( userNumber * 100 + someOtherVariable ) You can also have one or more statements in between the case statements. Repeating Things: Loops In this section, we look at how we can repeat a block of code for as long as a set read more..

  • Page - 80

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 55 for ( var loopCounter = 0; loopCounter < ➥ theBeatles.length; loopCounter++ ) { document.write( theBeatles[loopCounter] + "<br>" ); } </script> </body> </html> This example works because we are using a zero-based array in which the items have read more..

  • Page - 81

    56 CH APTER 2 ■ D ATA AND DECISIONS The results of the item key in indexKey at each iteration of the loop is written out alongside the value extracted from the array using that key in the same order as it occurs in the array: indexKey is Drummer item value is Ringo indexKey is SingerRhythmGuitar item value is John indexKey is SingerBassGuitar item value read more..

  • Page - 82

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 57 message += 'You entered the following:\n'; for ( var i = 0; i < arrayIndex-1; i++ ) { message += userNumbers[i] + '\n'; total += Number( userNumbers[i] ); } message += 'Total: ' + total + '\n'; alert( message ); read more..

  • Page - 83

    58 CH APTER 2 ■ D ATA AND DECISIONS We don’t need to initialize userInput because the code inside the loop sets a value for it before testing it for the first time. Continuing the Loop As you’ve already seen, the break statement is great for breaking out of any kind of loop once a certain event has occurred. The continue keyword works like break read more..

  • Page - 84

    CHAPTER 2 ■ DATA A N D DE CIS IO NS 59 if ( isNaN( userInput ) ) { document.write( "Invalid data entered: please ➥ enter a number between 0 and 99 in numerals " ); continue; } userNumbers[arrayIndex] = userInput; arrayIndex++; read more..

  • Page - 85

    read more..

  • Page - 86

    61 ■ ■ ■ 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 read more..

  • Page - 87

    62 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG Common DHTML scripts have several issues: • JavaScript dependence and lack of graceful degradation: Visitors with JavaScript turned off (either by choice or because of their company security settings) will not get the functionality, but elements that don’t do anything when they activate them or even pages that read more..

  • Page - 88

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 63 a stagehand—doing what she is good at backstage for the good of the whole production rather than being a diva who takes the whole stage for herself and shouts at the orchestra and her col- leagues every time something goes wrong or is not to her liking. Later on, the term DOM scripting got read more..

  • Page - 89

    64 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG Notice that this simply defines what layers are available, not how they interact. For exam- ple, something needs to convert content to structure (such as XSLT), and something needs to connect the upper four layers with the business logic. If you manage to keep all these layers separate, yet talking to each read more..

  • Page - 90

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 65 Figure 3-2. Microsoft Internet Explorer on Windows XP2 shows a warning message when you try to execute JavaScript locally. This separation of JavaScript into its own file makes it simpler to develop a web site that still works when the script is not available; and if a change in the site’s read more..

  • Page - 91

    66 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG A lot of older scripts use this information to determine whether a browser is capable of supporting their functionality. <script type="text/javascript"> if(browserName.indexOf('Internet Explorer')!=-1 && browserVersion.indexOf('6')!=-1) { document.write('<p>This is MSIE 6!</p>'); } else read more..

  • Page - 92

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 67 { // Images are supported var home=new Image(); home.src='home.gif'; var aboutus=new Image(); aboutus.src='home.gif'; } </script> The if condition checks whether the browser understands the images object, and only runs the code inside the condition if that is read more..

  • Page - 93

    68 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG One problem is that some in-between versions of Opera support the getElementById object, but fail to support the entire W3C DOM. To determine whether this is the case, test for support of the createTextNode as well: <script type="text/javascript"> if (document.getElementById && document.createTextNode) read more..

  • Page - 94

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 69 In web development terms, this means the following: • We start with a valid, semantically correct (X)HTML document with all the content— including relevant images with text alternatives as alt attributes—and a meaningful structure. • We add a style sheet to improve this structure’s appearance, legibility, read more..

  • Page - 95

    70 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG JavaScript and accessibility is holy war material. Many a battle between disgruntled devel- opers and accessibility gurus is fought on mailing lists, 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 read more..

  • Page - 96

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 71 That is all there is to make a web site with JavaScript accessible. That and, of course, all the assets of an accessible HTML document like allowing elements to resize with larger font set- tings, and providing enough contrast and colors that work for the color-blind as well as for people with normal read more..

  • Page - 97

    72 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG These do not mean much to somebody else (or yourself two months down the line) who tries to debug or understand the code. It is better to use descriptive names that tell exactly what the function does or what the variable is: • createTOC() • calculateDifference() • getCoordinates() • setCoordinates() • read more..

  • Page - 98

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 73 Simply check the following code examples; you might not understand now what they do (they present a small function that opens every link that has a CSS class of smallpopup in a new window and adds a message that this is what will happen), but just consider which one would be easier to read more..

  • Page - 99

    74 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG With indentation and curly braces on new lines: function addPopUpLink() { if(!document.getElementById || !document.createTextNode){return;} var popupClass='smallpopup'; var popupMessage= ' (opens in new window)'; var pop,t; var as=document.getElementsByTagName('a'); for(var read more..

  • Page - 100

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 75 code, it should be rather self-explanatory—it can speed up debugging immensely. The previ- ous example might make more sense for you with explanatory comments: /* 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 read more..

  • Page - 101

    76 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG /* 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() { if(!document.getElementById || !document.createTextNode){return;} // Assets of the link - the class to read more..

  • Page - 102

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 77 Functions can get values as parameters (sometimes called arguments) and can return val- ues after they finished testing and changing what has been given to them. You create a function by using the function keyword followed by the function name and the parameters separated by commas inside parentheses: function read more..

  • Page - 103

    78 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG tempLink.setAttribute('href',linkTarget); tempLink.appendChild(document.createTextNode(linkName)); return tempLink; } Another function could take these generated links and append them to an element. If there is no element ID defined, it should append the link to the body of the document. function read more..

  • Page - 104

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 79 If this is confusing now, don’t worry, you will see more examples later on. For now, it is just important to remember what functions are and what they should do: • Functions are there to do one task over and over again—keep each task inside its own function; don’t create monster functions that do read more..

  • Page - 105

    80 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG Other examples: t.className = t.className == 'hide' ? '' : 'hide'; var el = document.getElementById('nav') ? document.getElementById('nav') : document.body; You can also nest the ternary selector, but that gets rather unreadable: y = x <20 ? ( x > 10 ? 1 : 2) : 3; // equals read more..

  • Page - 106

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 81 <script type="text/javascript"> var demoVar=1 // Global variable alert('Before withVar demoVar is' +demoVar); function withVar() { var demoVar=3; } withVar(); alert('After withVar demoVar is' +demoVar); function withoutVar() { demoVar=3; } withoutVar(); read more..

  • Page - 107

    82 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG Notice that if you try to call the functions init() and validate(), you get an error, as they don’t exist any longer. Instead, you need to use myscript.init() and myscript.validate(). Wrapping all your functions in an object as methods is analogous to the programming classes used by some other languages such read more..

  • Page - 108

    CHA P TER 3 ■ FRO M DH TML TO DO M SCRIPTING 83 As you can see, all the functions are contained as methods inside the dynamicLinks object, which means that if we want to call them, we need to add the name of the object before the function name. The syntax is a bit different; instead of placing the function keyword before the name of the function, read more..

  • Page - 109

    84 CH APTER 3 ■ FROM DHTML TO DOM SCR IPTI NG We talked about accessibility and what it means for JavaScript, and you got a peek at a lot of coding practices. The general things to remember are • Test for the objects you want to use in your scripts. • Make improvements in an existing site that already works well without client-side scripting instead read more..

  • Page - 110

    85 ■ ■ ■ CHAPTER 4 HTML and JavaScript In this chapter, you finally get your hands dirty in real JavaScript code. You’ll learn how Java- Script 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 explain read more..

  • Page - 111

    86 CH APTER 4 ■ H T ML AND J A VASC RIPT <body> </body> </html> A markup document like this consists of tags (words or letters enclosed in tag brackets, like <p>) and text content. Documents should be well formed (meaning that every opening tag like <p> must be matched by a closing tag like </p>) and validate against read more..

  • Page - 112

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 87 <title>DOM Example</title> </head> <body> <h1>Heading</h1> <p>Paragraph</p> <h2>Subheading</h2> <ul id="eventsList"> <li>List 1</li> <li>List 2</li> <li><a read more..

  • Page - 113

    88 CH APTER 4 ■ H T ML AND J A VASC RIPT The user agent “sees” the document a bit differently. The DOM models a document as a set of nodes, including element nodes, text nodes, and attribute nodes. Both elements and their text content are separate nodes. Attribute nodes are the attributes of the elements. The DOM includes other sorts of nodes for read more..

  • Page - 114

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 89 ■Note Notice all the #text nodes between the elements? These are not text we added to the document, but the line breaks we added at the end of each line. Some browsers see those as text nodes while others don’t—which can be very annoying when we try to access elements in the document read more..

  • Page - 115

    90 CH APTER 4 ■ H T ML AND J A VASC RIPT Using window Methods: prompt(), alert(), and confirm() A different way of giving feedback and retrieving user-entered data is using methods the browser offers you via the window object, namely prompt(), alert(), and confirm(). The most commonly used window method is alert(), an example of which appears in Figure 4-4. read more..

  • Page - 116

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 91 } } </script> </head> <body> <form act ion="sitesearch.php" method="post" ➥ onsubmit="return checkSearch();"> <p> <label for="search">Search the site:</label> read more..

  • Page - 117

    92 CH APTER 4 ■ H T ML AND J A VASC RIPT We could extend the earlier example to ask the visitor to confirm a search for the common term JavaScript (see also Figure 4-6): function checkSearch() { if(!document.getElementById || ➥ !document.createTextNode){return;} read more..

  • Page - 118

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 93 Both alert() and confirm() send information to the user, but what about retrieving information? A simple way to retrieve user input is the prompt() method. This one takes two parameters, the first one being a string displayed above the entry field as a label and the second a preset value for the read more..

  • Page - 119

    94 CH APTER 4 ■ H T ML AND J A VASC RIPT { alert('Please enter a date'); return false } else { // Tell the user to change the date syntax either until // she presses Cancel or entered the right read more..

  • Page - 120

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 95 Summary 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, as the methods use the functionality and look and feel of the browser and offer a richer interface than HTML (specifically, the alert sound, read more..

  • Page - 121

    96 CH APTER 4 ■ H T ML AND J A VASC RIPT Accessing the Document via the DOM In addition to the window methods you now know about, you can access a web document via the DOM. In a manner of speaking, we have done that already with the document.write() examples. The document object is what we want to alter and add to, and write() is one read more..

  • Page - 122

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 97 <li><a href="http://www.google.com">Linked List Item</a></li> <li>List 4</li> </ul> <p>Paragraph</p> <p>Paragraph</p> </body> </html> Our script could now read the number of list items and paragraphs in the read more..

  • Page - 123

    98 CH APTER 4 ■ H T ML AND J A VASC RIPT If you open the HTML document in a browser now, you’ll see an alert like the one in Figure 4-9 with the right number of list elements and paragraphs. Figure 4-9. Output alert indicating the number of found elements You can access each of the elements of a certain name like you access an array—once again read more..

  • Page - 124

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 99 those that are inside the element with the ID eventsList (the name of the object with the ID replaces the document object): var events = document.getElementById('eventsList'); var eventlinkItems = events.getElementsByTagName('li'); for(var i = 0; i < eventLinkItems.length; i ++) { // Do something... } With the help read more..

  • Page - 125

    100 CH APTER 4 ■ H T ML AND J A VASC RIPT However, there are even more children. The text inside the paragraphs, headings, list ele- ments, and links also consists of nodes, as you may recall from Figure 4-2 earlier, and while they are not elements, they still follow the same relationship rules. Every node in the document has several valuable properties. •The read more..

  • Page - 126

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 101 Returning to the earlier example, you can access the UL element and get information about its children as shown here: HTML <ul id="eventsList"> <li>List 1</li> <li>List 2</li> <li><a href="http://www.google.com">Linked List Item</a></li> <li>List 4</li> read more..

  • Page - 127

    102 CH APTER 4 ■ H T ML AND J A VASC RIPT Figure 4-10. Nodes found by our script, including text nodes that in reality are line breaks 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 us to reach the link—by adding an ID to it: <ul read more..

  • Page - 128

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 103 { parentElm = parentElm.parentNode; } However, this loop will end in an “object required” 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 = document.getElementById('linkedItem'); var parentElm = read more..

  • Page - 129

    104 CH APTER 4 ■ H T ML AND J A VASC RIPT If the current object is the last child of the parent element, nextSibling will be undefined and cause an error if you don’t test for it properly. Unlike with childNodes, there are no short- cut properties for the first and last siblings, but you could write utility methods to find them; say, for read more..

  • Page - 130

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 105 <meta htt p-equiv="Content-Type" ➥ content="text/html; cha rset=utf-8" /> <title>Date example</title> <style type="text/css"> .error{color:#c00;font-weight:bold;} </style> <script t ype="text/javascript" src="che read more..

  • Page - 131

    106 CH APTER 4 ■ H T ML AND J A VASC RIPT if(errorMessage!='') { errorContainer.firstChild.nodeValue=errorMessage; dateField.focus(); return false; } else { return true; } } First, test whether DOM is supported and that all the needed elements are there: if(!document.getElementById || !document.createTextNode){return;} read more..

  • Page - 132

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 107 node) of the error SPAN, and sets the focus of the document back to the date entry field without submitting the form. if(errorMessage!='') { errorContainer.firstChild.nodeValue+=errorMessage; dateField.focus(); return false; } else { return true; } As Figure 4-11 shows, read more..

  • Page - 133

    108 CH APTER 4 ■ H T ML AND J A VASC RIPT mainImage.src='dynamiclogo.gif'; mainImage.alt='Generico Corporation - We do generic stuff'; mainImage.title='Go back to Home'; All the attributes defined in the HTML specifications are available and can be accessed. Some are read-only for security reasons, but most can be set and read. You can also come up with your own read more..

  • Page - 134

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 109 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). You can not only change existing elements, but also create new ones and replace or remove old ones read more..

  • Page - 135

    110 CH APTER 4 ■ H T ML AND J A VASC RIPT Let’s use these methods to counteract a problem that is quite common in web design: replacing Submit buttons with links. There are two ways to submit form data: a Submit button or an image button (actually, there are three—if you count hitting the Enter key). Submit buttons are a thorn in the side read more..

  • Page - 136

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 111 In code, this could be <!DOCTYPE HTM L PUBLIC "-//W3C//DTD HTML 4.01//EN" ➥ "http://www.w3.org/TR/html4/strict.dtd"> <html dir="ltr" lang="en"> <head> <meta htt p-equiv="Content-Type" ➥ content="text/html; cha rset=utf-8"> read more..

  • Page - 137

    112 CH APTER 4 ■ H T ML AND J A VASC RIPT When JavaScript is available, the visitor gets a link to submit the form; otherwise, he gets a Submit button, as shown in Figure 4-12. Figure 4-12. Depending on JavaScript availability, the user gets a link or a button to send the form. However, the function has one major flaw: it will fail when there read more..

  • Page - 138

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 113 newLink.appendChild(newText); newLink.setAttribute('href','javascript:document.forms[0] ➥ .submit()'); inputs[i].parentNode.replaceChild(newLink,inputs[i]); if(i<inputs.length){i--}; } } window.onload=submitToLinks; This version of the script will not fail, and replaces both buttons with links. ■Note read more..

  • Page - 139

    114 CH APTER 4 ■ H T ML AND J A VASC RIPT A message like that is not very helpful—the least you should do is to allow visitors who cannot have scripting enabled (for example, workers in banks and financial companies that turn off scripting as it poses a security threat) to contact you. Modern scripting tackles this problem from the other side: we read more..

  • Page - 140

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 115 noJSmsg.parentNode.insertBefore(head,noJSmsg); var infoPara=document.createElement('p'); infoPara.appendChild(document.createTextNode(replaceMessage)); noJSmsg.parentNode.insertBefore(infoPara,noJSmsg); var linkPara=document.createElement('p'); var read more..

  • Page - 141

    116 CH APTER 4 ■ H T ML AND J A VASC RIPT // Add more tests as needed (cookies, objects...) var noJSmsg=document.getElementById('noscripting'); if(!noJSmsg){return;} var replaceMessage='<h1>Browser test succeeded<h1>'; replaceMessage='<p>We tested if you r browser is capable of '; read more..

  • Page - 142

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 117 Reading Element Attributes, Node Values, and Other Node Data • node.getAttribute('attribute'): Retrieves the value of the attribute with the name attribute • node.setAttribute('attribute', 'value'): Sets the value of the attribute with the name attribute to value • node.nodeType: Reads the type of the node (1 = read more..

  • Page - 143

    118 CH APTER 4 ■ H T ML AND J A VASC RIPT DOMhelp: Our 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, as the user agent might or might not read the line break as its own text node. It is read more..

  • Page - 144

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 119 // Simulate a debugging console to avoid the need for alerts initDebug:function(){}, setDebug:function(bug){}, stopDebug:function(){} } You’ve already encountered the last and first sibling functions earlier in this chapter; the only thing that was missing in those was a test for whether there really is read more..

  • Page - 145

    120 CH APTER 4 ■ H T ML AND J A VASC RIPT The first problem we might encounter is that the node has no children whatsoever, there- fore we check for hasChildNodes. The other problems are embedded elements in the node and whitespace such as line breaks and tabs being read as nodes by browsers other than MSIE. Therefore, we test the first child node and read more..

  • Page - 146

    CH A P T E R 4 ■ HTM L AND JAVAS CRIPT 121 closestSibling:function(node,direction) { var tempObj; if(direction==-1 && node.previousSibling!=null) { tempObj=node.previousSibling; while(tempObj.nodeType!=1 && tempObj.previousSibling!=null) { tempObj=tempObj.previousSibling; } read more..

  • Page - 147

    122 CH APTER 4 ■ H T ML AND J A VASC RIPT The final method is the one that removes the console from the document if it exists. Notice that we both need to remove the element and set the object property to null; otherwise testing for DOMhelp.debug would be true even if there is no console to write to. stopDebug:function() { read more..

  • Page - 148

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

  • Page - 149

    124 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) <body> <h3>Contact Details</h3> <address> Awesome Web Production Company<br /> Going Nowhere Lane 0<br /> Catch 22<br /> N4 2XX<br / > England<br /> </address> </body> </html> styleChange.js sc = { init:function(){ sc.head read more..

  • Page - 150

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 125 The script grabs the first H3 element in the document and gets the ADDRESS element via the closestSibling helper method of the DOMhelp library (the method makes sure that it retrieves the next element and not line breaks that are seen as text nodes). It then modifies the read more..

  • Page - 151

    126 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) The style collection contains all the style settings of the current element that you can modify by using the property notation of the different CSS selectors. A rule of thumb for the property notation is that you remove the dash in the CSS selector and use camelCase for the whole read more..

  • Page - 152

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 127 While setting style attributes directly is frowned upon in modern web design (you are effectively mixing behavior and presentation and you make maintenance a lot harder), there are situations where you will have to set style attributes directly via JavaScript—for example: • Fixing read more..

  • Page - 153

    128 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) You can remove the class by setting its value to an empty string. Again, removeAttribute() does not work reliably across different browsers. As you may be aware, HTML elements can have more than one CSS class assigned to them. A construct of the following kind is valid HTML—and read more..

  • Page - 154

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 129 return found; break; } } Don’t worry too much about the inner workings of this method—it will get clearer to you once you master the match() and replace() methods, which will be covered in Chapter 8. For now, all you need to know is how to use read more..

  • Page - 155

    130 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) The style sheet contains, among others, a class called hide that will hide any element it gets applied to. In this example, you use the off-left technique (http://css-discuss.incutio.com/ ?page=screenReaderVisibility) for that, which is possibly the most accessible way of hiding content. The read more..

  • Page - 156

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 131 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 - 157

    132 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) // Check for DOM and apply a class to the body if it is supported if(!document.getElementById || !document.createElement){return;} DOMhelp.cssjs('add',document.body,sc.DOMClass); sc.head=document.getElementsByTagName('h3')[0]; if(!sc.head){return;} read more..

  • Page - 158

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 133 /* JS disabled */ address{ background:#ddd; border:1px solid #999; border-top:none; font-style:normal; padding:.5em; width:15em; } h3{ border:1px solid #000; color:#fff; background:#369; padding:.2em .5em; width:15em; font-size:1em; } /* JS enabled */ body.dynamic read more..

  • Page - 159

    134 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) The address example can now—depending on JavaScript and DOM being available or not— have two completely different looks (one of these having two states) as shown in Figure 5-2. Figure 5-2. The three states of the address (nondynamic version, collapsed, and expanded) This works nicely if read more..

  • Page - 160

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 135 <body> <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 read more..

  • Page - 161

    136 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) peekaboo:function(e){ if(DOMhelp.cssjs('check',sc.ad,sc.hidingClass)){ DOMhelp.cssjs('remove',sc.ad,sc.hidingClass) } else { DOMhelp.cssjs('add',sc.ad,sc.hidingClass) } DOMhelp.cancelClick(e); } } DOMhelp.addEvent(window,'load',sc.init,false);. The head of the read more..

  • Page - 162

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 137 The script is not complex. You loop through all LINK elements in the document and for each one determine whether its attribute is either stylesheet or alternate stylesheet. You create a new list with links pointing to a function that disables all but the currently chosen style read more..

  • Page - 163

    138 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) tempA.appendChild(document.createTextNode(styleTitle)); tempA.setAttribute('href','#'); Apply an event handler to the link that triggers the setSwitch() method and sends the link itself as a parameter via the this keyword. You can then continue to add the new list items read more..

  • Page - 164

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 139 Paul Sowden pioneered this trick in 2001 at Alistapart.com with his article “Alternative Style: Working With Alternate Style Sheets” (http://www.alistapart.com/articles/alternate/). As Netscape 4 (remember this was 2001) did not support this method properly, Daniel Ludwin came up with “A read more..

  • Page - 165

    140 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) 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 }, peekaboo:function(e){ if(DOMhelp.cssjs('check',sc.ad,sc.hidingClass)){ read more..

  • Page - 166

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 141 noncoders changing your code, you could use a separate JavaScript include file containing an object called CSS with all the classes as parameters. Give it an obvious file name like cssClassNames.js, and document its existence in the project documentation. cssClassNames.js css={ // Hide read more..

  • Page - 167

    142 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) 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 }, peekaboo:function(e){ // More code read more..

  • Page - 168

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 143 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 }, peekaboo:function(e){ // More read more..

  • Page - 169

    144 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) Figure 5-3. The multiple-column height problem Let’s start with a list of news items, each containing a heading, a “teaser” pa ragraph, and a “more” link. exampleColumnHeightIssue.html (with dummy content) <ul id="news"> <li> <h3><a read more..

  • Page - 170

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 145 If you now apply a style sheet that floats the list items and the main list to the left and set some more text and layout styles, you get a multicolumn layout. The CSS to achieve this is pretty basic: columnHeightIssue.css #news{ width:800px; float:left; } #news li{ read more..

  • Page - 171

    146 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) fix:function(elm){ fixcolumns.getHighest(elm); fixcolumns.fixElements(elm); }, getHighest:function(elm){ fixcolumns.highest=0; var temp=fixcolumns.n.getElementsByTagName(elm); for(var i=0;i<temp.length;i++){ if(!temp[i].offsetHeight){continue;} read more..

  • Page - 172

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 147 The fix() method invokes two additional methods, one to find out the maximum height to apply to each of the items and another to apply this height. fixColumnHeight.js (excerpt) fix:function(elm){ fixcolumns.getHighest(elm); fixcolumns.fixElements(elm); }, The getHighest() read more..

  • Page - 173

    148 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) fixElements:function(elm){ var temp=fixcolumns.n.getElementsByTagName(elm); for(var i=0;i<temp.length;i++){ if(!DOMhelp.cssjs('check',temp[i],fixcolumns.moreClass)){ temp[i].style.height = fixcolumns.highest +'px'; } } } ■Note Notice that you need read more..

  • Page - 174

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 149 On Firefox 1.5, the effect appears as shown in Figure 5-4. Figure 5-4. A rollover effect in CSS using the :hover pseudo-selector In MSIE 6, you will not get this effect, as it does not support :hover for list items. However, it supports JavaScript; read more..

  • Page - 175

    150 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) listItemRollover.js (excerpt) newshl={ overClass:'over', init:function(){ alert('d'); if(!document.getElementById || !document.createTextNode){return;} var newsList=document.getElementById('news'); if(!newsList){return;} var newsItems=newsList.getElementsByTagName('li'); for(var read more..

  • Page - 176

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 151 } #news li.over{ background:#fff; } #news li.active{ background:#ffc; } 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 (as the link in this example is either in a heading or in a paragraph): read more..

  • Page - 177

    152 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) The result is two different states for the news item, as shown in Figure 5-5, depending on the user hovering over the text or over the links. Figure 5-5. Different rollover states for a single element Using JavaScript, you can also make the whole news item clickable, and this is read more..

  • Page - 178

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 153 flexible rounded corners, and so on. Therefore, developers started generating these via Java- Script rather than expecting them in the HTML. This makes the source document appear a lot cleaner, but for the end user the final DOM tree—including all generated content—is what he has read more..

  • Page - 179

    154 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) Events can be many things, for example: • The initial loading and rendering of the document • The loading of an image •The user clicking a button • The user pressing a key • The user moving the mouse over a certain element ■Note Picture an event handler like a read more..

  • Page - 180

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 155 Triggering events in this way has several issues: • You don’t send the element to the function; instead you need to find the element again. • You can only assign one function at a time • You hijack the event of this element for your script exclusively—methods of other read more..

  • Page - 181

    156 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) If you use this tool function to add your function to the page, you will not override the other functions that should be invoked by the page’s load event. It was and is a big step in the right direction. The preceding methods work—to my knowledge—for all browsers that read more..

  • Page - 182

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 157 If you wanted to add a hover effect by calling the function highlight() when the mouse is over the link and the function unhighlight() when the mouse leaves the link, you can add a couple more lines: var triggerLink=document.getElementById('info'); triggerLink.addEventListener( 'click', read more..

  • Page - 183

    158 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) You can use the same function for all three events and check the event type: function infoWindow(e){ switch(e.type){ case 'click': // Code to deal with the user clicking the link break; case 'mouseover': // Code to deal with the read more..

  • Page - 184

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 159 Event Bubbling Let’s go back to the HTML markup for the news list: exampleEventBubble.html <ul id="news"> <li> <h3><a href="news.php?item=1">News Title 1</a></h3> <p>Description 1</p > <p class="more"><a read more..

  • Page - 185

    160 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) aTest:function (e){ alert('a was clicked'); } } window.addEventListener('load',bubbleTest.init,false); Now all the list items will trigger the liTest() method when they are clicked, all the paragraphs will trigger the pTest() method, and all the links will trigger the aTest() read more..

  • Page - 186

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 161 In the DOM-1 event handler model, you did this by returning a false value in the function that was called: element.onclick=function(){ // Do other code return false; } If you click any of the links in the earlier example, they load the linked document. You can override read more..

  • Page - 187

    162 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) The script for collapsing the elements is not complex, but uses all the event handling ele- ments we talked about: newsItemCollapse.js newshl={ // CSS classes overClass:'over', // Rollover effect hideClass:'hide', // Hide things currentClass:'current', // Open item init:function(){ read more..

  • Page - 188

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 163 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 read more..

  • Page - 189

    164 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) 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); } The toggleNews() method grabs the current read more..

  • Page - 190

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 165 newsItemCollapse.js (excerpt) e.preventDefault(); e.stopPropagation(); }, 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 as read more..

  • Page - 191

    166 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) Instead of addEventListener(), MSIE has attachEvent(); instead of passing an event object to each listener, MSIE keeps one global event object in window.event. A developer named Scott Andrew came up with a portable function called addEvent() that works around the differences when it read more..

  • Page - 192

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 167 As MSIE uses a global event, you cannot rely on the event object being sent to your listen- ers, but you need to write a different function to get the element that was activated. Matters get confused even further as the properties of window.event are slightly different from the read more..

  • Page - 193

    168 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) Safari has a nasty bug (or feature—one is never sure): if you click a link, it does not send the link, but the text node contained in the link, as the target. A workaround is to check whether the element’s node name is really a link: getTarget:function(e){ var target = read more..

  • Page - 194

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 169 As you normally want to stop both of these things from happening, it might make sense to collect them into one function: cancelClick:function(e){ if (window.event && window.event.cancelBubble && window.event.returnValue){ window.event.cancelBubble = true; read more..

  • Page - 195

    170 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) DOMhelp.addEvent(hl,'mouseover',newshl.hover,false); DOMhelp.addEvent(hl,'mouseout',newshl.hover,false); } var ps = newsList.getElementsByTagName('p'); for(i = 0;i<ps.length;i++){ DOMhelp.cssjs('add',ps[i],newshl.hideClass); } }, toggleNews:function(e){ read more..

  • Page - 196

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 171 necessary. Instead of hiding all paragraphs inside the list items individually, it is a lot easier to simply add a class to the list item and let the CSS engine hide all the paragraphs: listItemCollapseShorter.css (excerpt)—used in exampleListItemCollapseShorter.html #news li.hide p{ read more..

  • Page - 197

    172 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) 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 read more..

  • Page - 198

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 173 When you take another look at code you have created, the following ideas are always good to keep in the back of your head: • Any idea that avoids nested loops is a good one. • Properties of the main object are a good place to store information that is of interest for read more..

  • Page - 199

    174 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) The problem with this solution is that it relies heavily on browser-specific code and does not work on Safari or Opera. This might change in the future, so be sure to visit Dean’s site from time to time. A different solution that is supported by all JavaScript-capable read more..

  • Page - 200

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 175 However, there is nothing stopping you from checking keyboard entries in JavaScript with the keyup or keypress handler. The former is the W3C standard; the latter is not in the standards and occurs after keydown and keyup, but it is well supported in browsers. As an example read more..

  • Page - 201

    176 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) Figure 5-7. Testing an entry while it is being typed in keyChecking.js voucherCheck={ errorMessage:'A voucher can contain only numbers.', error:false, errorClass:'error', init:function(){ if (!document.getElementById || !document.createTextNode) { return; } var read more..

  • Page - 202

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 177 if(key<48 || key>57){ v.value=v.value.substring(0,v.value.length-1); voucherCheck.error=document.createElement('span'); DOMhelp.cssjs('add', voucherCheck.error, voucherCheck.errorClass); var message = document.createTextNode(voucherCheck.errorMessage) read more..

  • Page - 203

    178 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) It then retrieves the element (in this case via getElementById(), although you could as easily use DOMhelp.getTarget(e), but why make it more complex than needed?) and checks whether the error property is true. If it is true, there is already a visible error message and the Submit button read more..

  • Page - 204

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 179 ■Note Normally, it’d be enough to check whether the field contents 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, read more..

  • Page - 205

    180 CH APTER 5 ■ PRESENTATIO N AND BEH AVIOR (CSS AND E VENT HANDL ING) element or follows the default action of that element. Until recently, it was common practice and deemed safe to use numerical keys for these attributes—which works, until you have a user who has special characters in her name and needs to use Alt and the ASCII number of the char- read more..

  • Page - 206

    CHA P TER 5 ■ PRESENTATIO N AND BEH AVI OR (CSS AND E VENT HANDLING) 181 This is it—you should now have all the tools you need to go out there and “wow” the masses with stable, easy-to-maintain, slick JavaScript. In the next chapter, we will go through some of the most common uses of JavaScript and have a go at developing up-to-date read more..

  • Page - 207

    read more..

  • Page - 208

    183 ■ ■ ■ 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 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 examples, read more..

  • Page - 209

    184 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS Basics of Image Scripting In JavaScript you can reach and amend images in two ways: the DOM-2 way via getElementsByTagName() and getElementById(), or an older way, which involves the images collection that is stored in a property of the document object. As an example, read more..

  • Page - 210

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 185 Images have several properties, some of which are obvious, but others you may not have heard about: • border: The value of the border attribute in the HTML • name: The name attribute of the img tag • complete: A property that is true if the image has finished read more..

  • Page - 211

    186 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS ■Note Notice that if the dimensions of the image have been defined via the HTML width and height attributes, and you change its source, you don’t automatically change its dimensions. For an example, acti- vate the Set other picture button in the demo. This can read more..

  • Page - 212

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 187 Rollover Effects Rollover or hover effects were the absolute craze when JavaScript first got supported widely in the most common user agents. Many scripts were written, and a lot of small tools came out that allowed “instant rollover generation without any need to read more..

  • Page - 213

    188 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS Macromedia Dreamweaver use the image object preloading technique explained earlier in conjunction with the name attribute: examplePreloadingRollover.html (excerpts) <a href="contact.html" onmouseover="rollover('contact',1)" onmouseout="rollover('contact',0)"> <img read more..

  • Page - 214

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 189 <li> <a href="option2.html"> <img src="but_2.gif" class="roll" alt="option two" /> Option 2 </a> </li> [... code snipped ...] </ul> Then you plan your script. The main object of the script will read more..

  • Page - 215

    190 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS If the image has the right CSS class attached to it, you read its source attribute, replace the full stop in it by the suffix defined in the overSrcAddOn property followed by a full stop, and store the result in the oversrc variable. automatedRollover.js (continued) read more..

  • Page - 216

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 191 The outcome of the demo page as shown in Figure 6-3 features rollovers with highlight images that are already loaded into the browser’s cache when the user hovers over the original ones. Figure 6-3. The preloaded and automated rollovers As much as you can try to use read more..

  • Page - 217

    192 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS You can see the effect by opening exampleCSSonlyRollover.html in a browser. The CSS in question constrains the link to a certain size and achieves the rollover effect by shifting the background image in the hover state to the left via a negative background-position value that is read more..

  • Page - 218

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 193 However, as this navigation could be the first level in a multilevel navigation menu, it might also be that the highlight is not a STRONG element but a class on the list item instead: <ul id="nav"> <li><a read more..

  • Page - 219

    194 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS if( lis[i].getElementsByTagName( 'strong' ).length > 0 | | DOMhelp.cssjs('check', lis[i], pr.currentLink) ) { pr.current = i; } Each of the list items gets a new property called index, which contains its counter value in read more..

  • Page - 220

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 195 Which of the two gets applied depends on whether the user hovers his mouse over the list item or not—something you can find out by comparing the event type with mouseover. Set the style of the navigation’s background position accordingly, and then call the init() method read more..

  • Page - 221

    196 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS and named class consists of the dynamicLink property value and the current index plus one (as it is easier for humans to have a first class called item1 class instead of item0): parentCSSrollover.js as used in parentCSSrollover.html (abbreviated) pr = { navId : read more..

  • Page - 222

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 197 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 read more..

  • Page - 223

    198 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS All future maintainers have to do to change the order of the images or add or delete images is to change the HTML; there is no need to change the JavaScript at all. Provided that you sup- ply an appropriate style sheet, visitors without JavaScript read more..

  • Page - 224

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 199 You should also allow the maintainer to change the look and content of the forward and back- ward links and the text content of the image counter. As for methods, all you need (apart from the helper methods contained in DOMhelp) is a global initialization method, a method read more..

  • Page - 225

    200 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS Let’s go through the methods in the script step by step. First up is the global initialization method init(): 1. Test for DOM support. 2. If the test is successful, loop through all the UL elements of the document. 3. For each UL, check whether it has the class defining it read more..

  • Page - 226

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 201 Other dynamically assigned CSS classes you have to define to make the slide show work are a hide class to remove the backward link when the first image is shown or the forward link when the last image is shown and a show class to overrule the hiding you achieved read more..

  • Page - 227

    202 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS A new SPAN element that acts as the image counter is next. Get the counterLabel property of the main object and replace the # character with the current list’s currentSlide property value and add 1 to it (because humans start counting at 1 and not at 0 like read more..

  • Page - 228

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 203 counteracts the Safari bug of sending the text contained in a link as the target instead of the link itself. The method then grabs the list the event was triggered in by reading the closestSibling() of the target’s parentNode. photoListInlineSlides.js (continued) showSlide read more..

  • Page - 229

    204 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS photoListInlineSlides.js (continued) count = ( t == parentList.fwd ) ? count+1 : count-1; action = ( count > 0 ) ? 'remove' : 'ad d' ; DOMhelp.cssjs( action, parentList.rew, ➥ inlineSlides.hideLinkClass ); action = ( count < photoCount ) ? read more..

  • Page - 230

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 205 Preventing this issue is rather easy though: all you need to amend is the showSlide() method so as not to do anything 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 read more..

  • Page - 231

    206 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS initSlideShow : function( o ) { var p, temp, count; p = document.createElement( 'p' ); DOMhelp.cssjs( 'add', p, inlineSlides.slideCounterClass ); o.parentNode.insertBefore( p, o.nextSibling ); o.rew = DOMhelp.createLink( '#', ' ' ); read more..

  • Page - 232

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 207 DOMhelp.cssjs( action, parentList.fwd, ➥ inlineSlides.hideLinkClass ); photo = parentList.getElementsByTagName( 'li' )[count]; var counterText = parentList.count.firstChild counterText.nodeValue = counterText.nodeValue. ➥ replace( /\d/, count + 1 ); read more..

  • Page - 233

    208 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS If you open the example in a browser with JavaScript enabled, you get a list of small thumbnails and a larger image. Clicking the thumbnails will replace the larger image with the one the thumbnail points to, as shown in Figure 6-9. Figure 6-9. A slide show with small read more..

  • Page - 234

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 209 The CSS for the slide show is pretty simple: miniSlides.css (excerpt) .minislides, .minislides * { margin:0; padding:0; list-style:none; border:none; } .minislides{ clear:both; margin:10px 0; background:#333; } .minislides,.minislides li{ float:left; } .minislides li read more..

  • Page - 235

    210 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS miniSlides.js (excerpt) init : function() { if( !document.getElementById || !document.createTextNode ) { return; } var lists = document.getElementsByTagName( 'ul' ); for( var i = 0; i < lists.length; i++ ) { if( read more..

  • Page - 236

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 211 miniSlides.js (excerpt) var links = o.getElementsByTagName( 'a' ); for(i = 0; i < links.length; i++){ DOMhelp.addEvent( links[i], 'click', minislides.showPic, ➥ false ); links[i].onclick = function() { return false; } // read more..

  • Page - 237

    212 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS 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. A lot of DHTML scripts use read more..

  • Page - 238

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 213 ■Note This is a point of agreement between different browser makers wanting to stop security vulnerabil- ities. Opening a new window without a visible location bar can allow a malicious attacker to open a pop-up on a third-party site via Cross-Site Scripting (XSS), make it read more..

  • Page - 239

    214 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS 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 read more..

  • Page - 240

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 215 Window Methods The window object also has a number of methods, some of which have been discussed in earlier chapters. The most common ones apart from those that provide user feedback are for opening new windows and timed execution of functions. User Feedback Methods The read more..

  • Page - 241

    216 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS Not all of the properties listed here are supported in all browsers, but they can be used in most of them: • height: Defines the height of the window in pixels. • width: Defines the width of the window in pixels. • left: Defines the horizontal position of the window on read more..

  • Page - 242

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 217 You can try to open the window when the page loads: exampleWindowPopUp.html (excerpt) function popup() { var windowprops = "width=200,height=200,top=100,left=100"; var myWin = window.open( "grid.html", "mynewwin" ,windowprops ); } window.onload = popup; Notice that read more..

  • Page - 243

    218 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS In this example, you define the name of the window as “mynewwin”, and you target a link to open http://www.yahoo.co.uk/ in there: exampleParameterLinkWindowPopUp.html (excerpts) function popup( url ) { var windowprops = "width=200,height=200,top=100,left=100"; var myWin = read more..

  • Page - 244

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 219 automaticPopupLinks.js (excerpt) init : function() { if( !document.getElementById || !document.createTextNode ) { return; } var label; var allLinks = document.getElementsByTagName( 'a' ); for( var i = 0; i < allLinks.length; read more..

  • Page - 245

    220 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS You can use the close() method to get rid of windows, and you can reach the window that opened the pop-up window via the window.opener property. Suppose that you’ve opened two new windows from a main document: w1 = window.open( 'document1.html', 'win1' ); w2 = window.open( read more..

  • Page - 246

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 221 ■Caution If you try to close the initial window with window.opener.close(), some browsers will give a security alert asking the user if he wants to allow that. This is another security feature to prevent site owners with malicious intentions spoofing a different read more..

  • Page - 247

    222 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS Animation with Window Intervals and Timeouts You can use the setInterval() and setTimeout() window methods to allow for timed execu- tion of code. setTimeout means you wait a certain time before executing the code (once only); setInterval() executes the code every time the read more..

  • Page - 248

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 223 .warning{ width:300px; padding:2em; background:#fcc; border:1px solid #c00; font-size:2em; } The difference between the two is shown in Figure 6-14. Figure 6-14. Warning message without and with JavaScript The user can click the “remove warning” link to get rid read more..

  • Page - 249

    224 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS All the removeWarning() method needs to do is remove the warning message from the document, clear the timeout, and stop the default action of the link. timeout.js (continued) removeWarning : function( e ){ warn.w.parentNode.removeChild( warn.w ); window.clearTimeout( read more..

  • Page - 250

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 225 However, for web sites this is not formulated as clearly. The 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 - 251

    226 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS autoSlides.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 read more..

  • Page - 252

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 227 autoSlides.js (continued) for( var i = 0; i < uls.length; i++ ) { if( !DOMhelp.cssjs( 'check', uls[i], ➥ autoSlides.slideClass ) ){ continue; } DOMhelp.cssjs( 'swap', uls[i], autoSlides.slideClass,_ read more..

  • Page - 253

    228 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS autoSlides.js (continued) playSlide : function( e ) { var t = DOMhelp.getTarget( e ); while( t.nodeName.toLowerCase() != 'a' && t.nodeName.toLowerCase() != 'body' ){ t = t.parentNode; } var parentList = read more..

  • Page - 254

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 229 The showSlide() method changes quite drastically, but you will see that some of the ini- tially confusing parts of the other methods (like what the slideLists array is good for) make the method rather easy. Remember that you define in playSlide() that the interval should call read more..

  • Page - 255

    230 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS This complexity is just a taste of what awaits the JavaScript developer when it comes to animation and timed execution of code. Creating a smooth, stable, cross-browser animation in JavaScript is tricky and needs a lot of testing and knowledge of browser issues. Luckily, there are read more..

  • Page - 256

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 231 newa.appendChild( document.createTextNode ➥ ( 'back to previous page' ) ); newa.onclick = function() { window.back();return false; } p.replaceChild( newa, p.firstChild ); } } window.onload = backlink; ■Caution The danger of these methods is that read more..

  • Page - 257

    232 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS 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; } read more..

  • Page - 258

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 233 ad.offer = document.getElementById( ad.adID ); if( !ad.offer ) { return; } DOMhelp.cssjs( 'add', ad.offer, ad.adDynamicClass ); var closeLink = DOMhelp.createLink( '#', ad.closeLinkLabel ); DOMhelp.cssjs( 'add', closeLink, ad.closeLinkClass ); read more..

  • Page - 259

    234 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS examplePicturePopup.html (excerpt) <a class="picturepop" href="pictu res/thumbs/dog7.jpg">Sleeping Dog</a> The script needs to do something that wasn’t explained here before, namely reading the position of elements. You cover the main document with an element by read more..

  • Page - 260

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 235 picturePopup.js (continued) openPopup : function( e ) { var t = DOMhelp.getTarget( e ); if( t.nodeName.toLowerCase() != 'a' ) { t = t.parentNode; } if( !pop.popContainer ) { t.innerHTML = pop.displayPrefix + t.preset; read more..

  • Page - 261

    236 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS picturePopup.js (continued) positionPopup : function( o ) { var x = 0; var y = 0; var h = o.offsetHeight; while ( o != null ) { x += o.offsetLeft; y += o.offsetTop; o = o.offsetParent; } read more..

  • Page - 262

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 237 Figure 6-17. An example of a dynamically displayed photo The beauty of this approach is that it is not only limited to photos. With just a simple mod- ification, you can display other documents inside the current one. The trick is to dynamically read more..

  • Page - 263

    238 CH APTER 6 ■ C O MMON USE S OF JA VASCRIPT : IMAGES A N D WINDO WS 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 read more..

  • Page - 264

    CH A P T E R 6 ■ COMMON US ES OF J A VASC RIPT : IMAGES AND WIN D OWS 239 • If you use pop-up windows, tell visitors in the link opening the window that there will be a new window. This informs visitors with user agents that don’t necessarily support mul- tiple windows that there might be a change they have to deal with; it also read more..

  • Page - 265

    read more..

  • Page - 266

    241 ■ ■ ■ CHAPTER 7 JavaScript and User Interaction: Navigation and Forms In this chapter, we will talk about two more common uses of JavaScript: navigation and forms. Both mean a lot of user interaction and therefore need to be planned and executed thought- fully. The success of a web site stands and falls with the ease of its navigation, and there is nothing read more..

  • Page - 267

    242 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS The Fear of the Page Reload A lot of JavaScript enhancements to forms and web navigation are made to prevent visitors from having to reload the page or load a lot of pages before reaching the information they came for. This is an admirable idea and can work wonderfully; read more..

  • Page - 268

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 243 Figure 7-1. Using a select box for navigation Open the demo page exampleSelectNavigation.html and select one of the options from the drop-down. If you are connected to the Web and you have JavaScript enabled, you will be immediately sent to the address you choose. read more..

  • Page - 269

    244 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS exampleSaferSelectNavigation.html (excerpt) <form method="post" action="redir .php"> <p> <label for="url">Please select your destination:</label> <select id= "url" name="url"> <option v alue="http://www.apress.com">The publisher</option> read more..

  • Page - 270

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 245 Browser Navigation Browsers give you several objects you can use for automatic redirection or navigation around the browser’s history. You already encountered the window.back() method in the last chapter. The window object also provides the properties window.location and read more..

  • Page - 271

    246 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS The list of pages the user visited before reaching the current one is stored in the window.history object. This object has only one single property, called length, which stores the number of already visited pages. It has, however, three methods you can use: • back(): Go back one read more..

  • Page - 272

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 247 [... content ...] <p class="back"> <a href="#toolinfotoc">Back to <acronym title="Table of Contents">TOC</acronym></a> </p> </div> <div class="infoblock"> read more..

  • Page - 273

    248 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS However, this does not take another aspect of in-page navigation into consideration: the page could have been requested with a predefined target coming from another link. Try it out by adding an anchor to the URI—for example, exampleLinkedAnchorsFixed.html#use—in your browser. You’ll read more..

  • Page - 274

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 249 The init() method begins with checking whether DOM is supported and all necessary elements are available. Only then you add the class to the parent element to hide all the section elements automatically, via CSS. innerNav.js (excerpt) init : function(){ if( read more..

  • Page - 275

    250 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS there, you need to define currentLink as the first anchor in the menu instead. The init() method finishes by calling the showSection() method with the currentLink as a parameter. innerNav.js (continued) if( !iv.currentLink ) { iv.currentLink = toclinks[0]; read more..

  • Page - 276

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 251 Why two nodes up? If you remember the HTML, you nested the links inside headings and nested the headings and the rest of the section inside DIV elements: exampleLinkedAnchors.html (excerpt) <li><a href="#demo">Demo</a></li> [... code read more..

  • Page - 277

    252 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS Figure 7-2. A panel interface created from an anchor—target list 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 This read more..

  • Page - 278

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 253 innerNavNamed.js iv = { // CSS classes dynamicClass : 'dyn', currentLinkClass : 'current', showClass : 'show', // IDs parentID : 'toolinfo', tocID : 'toolinfotoc', The first change is that you need only one current property as well as two new read more..

  • Page - 279

    254 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS 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 read more..

  • Page - 280

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 255 innerNavNamed.js (continued) showSection : function( sectionName ){ if( iv.current != null ){ DOMhelp.cssjs( 'remove', iv.sections[iv.current], ➥ iv.showClass); DOMhelp.cssjs( 'remove', iv.sectionLinks[iv.current], ➥ iv.currentLinkClass read more..

  • Page - 281

    256 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS </li> <li><a href="portal.php">Company Portal</a></li> <li><a href="mailserver.php">eMail Solutions</a> <ul> <li><a href="privatemail.php">Private read more..

  • Page - 282

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 257 Basic web site usability and common sense dictate that the currently shown page should not link to itself. To keep this from happening, replace the current page link with a STRONG ele- ment, which also means that users without CSS understand where they are in the read more..

  • Page - 283

    258 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS The demo document exampleDynamicSiteNavigation.html does this, with the Mini CMS page defined as the current page to show the effect. Figure 7-4 shows how this looks in Firefox 1.5 on Windows XP. Figure 7-4. A tree menu with JavaScript and CSS The script’s skeleton is rather read more..

  • Page - 284

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 259 siteNavigation.js (excerpt) init : function() { var triggerLink; if( !document.getElementById || !document.createTextNode ) { return; } var nav = document.getElementById( sn.navID ); if( !nav ){ return; } read more..

  • Page - 285

    260 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS All the event listener method changeSection() needs to do is to 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 read more..

  • Page - 286

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 261 You can show and hide the nested UL elements by setting the values of their display prop- erties to block and none, respectively. This also takes the contained links out of the normal tabbing order: keyboard users won’t have to tab through all the links in the read more..

  • Page - 287

    262 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS Instead of taking the first link in the parent node as the trigger link, you create a new link element, set its href attribute to a simple hash to make it clickable, and add the parent indica- tor image defined earlier as its content. Then insert the linked image read more..

  • Page - 288

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 263 The rest of the method stays the same with one difference—you change the content of the link in addition to applying the different classes. siteNavigationIndicator.js (continued) var firstList = t.parentNode.getElementsByTagName( 'ul' )[0]; if( DOMhelp.cssjs( 'check', read more..

  • Page - 289

    264 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS Figure 7-5. Paginating a large set of data rows 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 read more..

  • Page - 290

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 265 <td>The final Rip-Off</td> <td>Double CD with all the songs</td> </tr> [... and so on ...] </tbody> </table> We used pagination in the last chapter in the slide show example, although the example showed one item at a time. read more..

  • Page - 291

    266 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS 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” (that 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 - 292

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 267 pagination.js (excerpt) tablebody = ts[i].getElementsByTagName( 'tbody' )[0]; ts[i].datarows = tablebody.getElementsByTagName( 'tr' ); ts[i].datarowsize = ts[i].datarows.length; ts[i].current = null; Apply the dynamic class to the table and read more..

  • Page - 293

    268 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS It would be good to show the same menu below the table as well. Instead of re-creating all these elements once more, it is enough to clone the paragraph and insert it after the table via parentNode, insertBefore(), and nextSibling. Then, store the “previous” and “next” links of read more..

  • Page - 294

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 269 pagination.js (excerpt) navigate : function( e ){ var start, table; var t = DOMhelp.getTarget( e ); while( t.nodeName.toLowerCase() != 'a' ){ t = t.parentNode; } It then needs to check whether the link is active or not by read more..

  • Page - 295

    270 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS The showSection() method calls the changePaginationNav() method to update the links and the counter and tests whether there is already a current parameter on the table. If there is one, this means data rows exist that need to be removed. You get rid of them by looping read more..

  • Page - 296

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 271 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', read more..

  • Page - 297

    272 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS Summary of Navigation with JavaScript Powering a site’s navigation with JavaScript is a very tempting use of your skills, as it is “out there” and still quite amazing for “wowing” clients with a fancy interface. The main thing to remember is that you should turn off read more..

  • Page - 298

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 273 <p><input type="text" id="email" value="y ou@example.com" ➥ name="email" /></p> </fieldset> <fieldset> <legend>Your message</legend> <p><label for="subject">Subject</label> <select id= "subject" read more..

  • Page - 299

    274 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS The form features fieldsets for grouping elements into logical units and labels for connect- ing explanation texts with specific form elements. This helps a lot with form accessibility, as it provides logical organization and avoids ambiguity. Basics of Forms with JavaScript Reaching read more..

  • Page - 300

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 275 Both methods simulate browser functionality—namely activating a Reset or a Submit but- ton—and you should make sure that you don’t use them to take away necessary interactivity from the user. There is a good reason that forms get submitted when the user clicks a read more..

  • Page - 301

    276 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS One special element type is the select box, which comes with a collection of its own, a property called options—but more on this later. Each element has a range of methods that is also dependent on the type of element. None of these methods expect any parameters. • blur(): read more..

  • Page - 302

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 277 Globally Supported Properties All form elements initially supported the type, name, form, and value properties. One recent change is that file upload fields do not support setting value any longer, as it would allow a malicious scripter to inject her own files to upload to read more..

  • Page - 303

    278 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS Using blur() and focus() You can use blur() to take the user agent’s focus away from an element or focus() to set it. The danger of this is that blur() does not take any target it should set the focus to, which means that user agents might focus on the read more..

  • Page - 304

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 279 When the user hasn’t changed anything on the field, both values would be you@example.com. However, if the user were to enter me@otherexample.com in the field, the two values become different. It is tricky to find an example for defaultValue that does not mean you have read more..

  • Page - 305

    280 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS Figure 7-6. Bulk changing of check boxes via JavaScript There are three buttons in the example that call the same function—changeBoxes()— when the user clicks them. Each button supplies a different numeric value for the function’s sole parameter—1 for select all, -1 for read more..

  • Page - 306

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 281 If this is confusing, remember that the checked property is a Boolean value. This means when it is true or 1, it is checked, and when it is false or 0, it is unchecked. If you were to use only the true or false keywords, you’d have to add read more..

  • Page - 307

    282 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS to make changes to defaultChecked appear visually. As the example HTML only has a radio group of two options, let’s choose a different example: exampleFormRadioGroup.html (excerpt) <form method="post" action="send. php"> <fieldset> <legend>Step 1 of 3 - read more..

  • Page - 308

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 283 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]; read more..

  • Page - 309

    284 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS 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 read more..

  • Page - 310

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 285 Figure 7-8. Changing the style and text content of a Submit button when the form gets sent 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 read more..

  • Page - 311

    286 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS From a JavaScript point of view, there is not much more you can do with an image input, except that you can provide a rollover state for it. Select Boxes Select boxes are probably the most complex and most versatile of form elements. Designers love them, as it lets them read more..

  • Page - 312

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 287 Reading out single-choice select boxes is pretty easy. For example, take the select box in the demo form: exampleSelectChoice.html (excerpt) <p> <label for="subject">Subject</label> <select id= "subject" name="subj ect"> <option v read more..

  • Page - 313

    288 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS Instead of using selectedIndex, you’ll have to loop through all the options and test the selected property of each one: exampleSelectChoice.html (excerpt) function checkMultiple() { var f = document.forms[0]; var selectBox = f.elements['multisubject']; var choices=[]; for( var i read more..

  • Page - 314

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 289 Adding, Replacing, and Removing Options Select boxes are unique as form elements go, insofar as they allow you to add or remove options programmatically. You can add a new option by using the Option constructor and including it in the list of options: extraOption = new read more..

  • Page - 315

    290 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS exampleSelectChoice.html (excerpt) function insertBeforeOption( fieldName, n ) { var i = 0, j = 0, opts = [], var f = document.forms[0]; var selectBox = f.elements[fieldName]; var extraOption = new Option('DOM scripting', ➥ 'domscripting', 0,0); Then store the options of read more..

  • Page - 316

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 291 exampleSelectChoice.html (continued) } else { old[i] = opts[j]; j++; } } } Depending on the number of options in the select box, this could become a rather slow and demanding script. You can achieve the same effect a lot read more..

  • Page - 317

    292 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS When it comes to simply changing the interface or the number of options displayed in a form, it is quite safe to use change handlers. Let’s use the demo form as an example. You might have noticed that there are some fields that have a logical connection: the “other read more..

  • Page - 318

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 293 Figure 7-9. Showing and hiding form elements depending on user choices 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', read more..

  • Page - 319

    294 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS Next you need to find the elements to hide. By using the DOMhelp method closestSibling(), you can make sure you don’t try to hide line breaks but the elements that you actually want to reach. Store the elements in properties of the main object to make them accessible to the read more..

  • Page - 320

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 295 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' ) { read more..

  • Page - 321

    296 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS The main difference in the script is that you have to target each input element you want to disable individually. In the case of the radio buttons, this means that you have to go through a loop. The changes in the script are highlighted in bold and should be self-explanatory: read more..

  • Page - 322

    CHAPTER 7 ■ JAVA SCRIPT AND US ER INTERAC T ION : NAVIG A T ION A N D FORMS 297 The practical upshot of using disabled is that these elements cannot be reached via tab- bing any longer either—something that is still possible with elements that are hidden (unless you hide them by setting display to none as shown earlier in the site navigation read more..

  • Page - 323

    298 CH APTER 7 ■ J A VASCRIPT AND USER INTER ACTIO N : NAVIGATION AND FORMS In the next chapter, we will leave the world of browser and client-side scripting and focus on how we can make JavaScript talk to the back end and server-side scripts. This will also enable you to take a look at that new kid on the scripting block: Ajax. read more..

  • Page - 324

    299 ■ ■ ■ CHAPTER 8 Back-End Interaction with Ajax You finally reached the chapter where I am going to talk about the new amazing JavaScript- related phenomenon, Ajax. The good news is that you can use Ajax to create really nice, slick interfaces, and you can extend JavaScript’s reach much further than the browser and the cur- rently displayed document. The read more..

  • Page - 325

    300 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX When and if you install XAMMP, you can unpack the chapter examples in a directory— called, for example, jsbook—in the htdocs directory of the server installation, which could be c:\xammp\htdocs\. To see the examples, you open a browser and type in http://localhost/ jsbook/ as the location. ■Tip In addition read more..

  • Page - 326

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 301 Figure 8-1. Ajax vs. traditional request At first glance, this appears to add an extra layer of complexity to the whole matter. How- ever, the really cool thing about it is that the communication between the Ajax engine and the browser happens via JavaScript and not via page reloads. In practical terms, read more..

  • Page - 327

    302 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX Figure 8-2. Loading external files via Ajax The magic wand behind all of this is an object called XMLHttpRequest, or XHR for short. This is a nonstandard object insofar as it is not part of an official standard on the W3C site (it is a working draft at the moment: read more..

  • Page - 328

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 303 Let’s go through the example step by step so you can see what the different parts do. The HTML contains links pointing to text files and calls the simplexhr.doxhr method with two parameters: an ID of an HTML element to send the text to and the URL of the text: exampleXHR.html (excerpt) read more..

  • Page - 329

    304 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX The script starts by checking for the DOM and whether the element you want to write content into is available. If it is, it gets stored in a property called outputContainer to make it available for all other methods in the script. simpleXHR.js (continued) var request; try{ read more..

  • Page - 330

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 305 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 can be (among some other read more..

  • Page - 331

    306 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX The readyState property of the request object contains a numeric value that describes what is happening to the connection. It is incremented throughout the connection attempt. The different possible values for readyState and their corresponding request states are as follows: • 0: There is no connection—it is read more..

  • Page - 332

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 307 The other states cannot be read safely cross-browser, which is why we skip 2 and 3 and check whether the request was finished by comparing readyState with 4. simpleXHR.js (continued) if( request.readyState == 4 ) { if ( /200|304/.test( request.status ) ) { read more..

  • Page - 333

    308 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX If the request didn’t succeed, the failed() method shows an alert() dialog telling the user about the problem. (This is not very clever or pretty, but should do for the moment.) Returning true after the user has clicked the dialog’s OK button causes the link to be followed. You can test this by read more..

  • Page - 334

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 309 ■Note The Ajax acronym doesn’t really work for these examples, as the process lacks the XML component. For this reason, this approach is known as AHAH and is defined as a microformat with code examples at http://microformats.org/wiki/rest/ahah. Et Tu, Cache? Normally the browser cache is our read more..

  • Page - 335

    310 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX You want to retrieve this data via XHR and display it as a table in the page. Figure 8-5 shows the different stages of the request. Figure 8-5. Retrieving and showing XML data as a table The main part of the script does not have to change: simpleXMLxhr.js simplexhr = { doxhr : function( container, read more..

  • Page - 336

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 311 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 - 337

    312 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX Notice that when you create tables on the fly, MSIE will not display them unless you nest the rows and cells in a TBODY element. Firefox won’t mind. Next, loop over all the album elements of the data that was retrieved. simpleXMLxhr.js (continued) var albums = data.getElementsByTagName( 'album' ); read more..

  • Page - 338

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 313 Add the resulting table as a new child element to the output container, and return false to stop the link from loading the XML as a new document. The failed() method stays the same. simpleXMLxhr.js (continued) simplexhr.outputContainer.appendChild( table ); return false; }, failed : read more..

  • Page - 339

    314 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX ■Note This example uses regular expressions, which you may not know yet, but which we will talk about in more detail in the next chapter. It suffices to say that regular expressions are delimited with slashes and match a certain pattern of text. If there are parentheses inside the slashes, read more..

  • Page - 340

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 315 <artist>Ms Kittin</artist> <title>I.com</title> <comment>Good electronica</comment> </album> </albums> Converted to JSON, this is as follows: albums.json { 'album': [ { 'id' : '1', 'artist' : 'Depeche Mode', read more..

  • Page - 341

    316 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX This will give you all the content as objects that you can access via either property notation or associative array notation (the latter is shown in the id example, the former in all the others): exampleJSONxhr.js (excerpt) var albums = data.album; for( var i = 0; i < albums.length; i++ ) read more..

  • Page - 342

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 317 The server-side component is a pass-through or proxy script that takes a URL, loads the content of the document, and sends it back to the XHR. The script needs to set the right header to tell the XHR that the data it returns is XML. If the file cannot be found, the script returns an read more..

  • Page - 343

    318 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX The relevant part in the HTML is the link that calls the doxhr() method with the element to output the news in and the RSS URI as parameters: exampleExternalRSS.html (excerpt) <p> <a href="http://rss.news.yahoo.com/rss/topstories" onclick="return readrss.doxhr('newsContainer',this.href)"> read more..

  • Page - 344

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 319 The script is once again a simple XHR. The difference is that instead of linking to the URL directly, you pass it to the PHP script as a GET parameter: externalRSS.js readrss = { doxhr:function( container, url ) { [... code snipped as it is the same as in the last example ...] read more..

  • Page - 345

    320 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX If there are items to be displayed, you define the necessary variables and loop through them. As some RSS feeds have lots of entries, it makes sense to constrain how many you dis- play; in this case, you choose 5. You read the link and the title for each item and add a new list item with an read more..

  • Page - 346

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 321 10 seconds and try again, and—pending your connection not being dead slow or Yahoo being down—you will get the headlines. Figure 8-7. Allowing an XHR connection to time out The differences in the script are that you need a property to define how long to wait before a timeout is triggered, one to read more..

  • Page - 347

    322 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX XHRtimeout.js (continued) request.onreadystatechange = function() { if( request.readyState == 1) { readrss.toolong = window.setTimeout( function(){ if( request.readyState == 1 ) { readrss.timedout = true; read more..

  • Page - 348

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 323 A Larger Ajax Example: Connected Select Boxes Let’s take a look at a larger Ajax example—I call it that although you won’t be using XML. Con- nected select boxes are a classic example of what JavaScript can do for you to make an interface faster. One common use for them is the flight offer read more..

  • Page - 349

    324 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX Figure 8-8. Connected select boxes 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 read more..

  • Page - 350

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 325 The PHP script will return 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 read more..

  • Page - 351

    326 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX Now start to flesh out the skeleton: selectBoxes.js dynSelect = { AJAXlabel : 'Only reload the results, not the whole page', AJAXofferClass : 'ajax', containerID : 'formOutput', backlinkID : 'back', The init() method tests whether the W3C DOM is supported, retrieves the first form, and stores the read more..

  • Page - 352

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 327 selectBoxes.js (continued) p.appendChild( dynSelect.cb ); var lbl = document.createElement( 'label' ); lbl.htmlFor = 'xhr'; lbl.appendChild( document.createTextNode( dynSelect.AJAXlabel ) ); p.appendChild( lbl ); f.insertBefore( p, f.firstChild ); dynSelect.addEvent(f, read more..

  • Page - 353

    328 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX if( request.readyState == 4 ) { if( request.status && /200|304/.test( request.status ) ) { dynSelect.retrieved( request ); } else{ dynSelect.failed( request ); } } } Determine whether the read more..

  • Page - 354

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 329 Next, open the request. In addition to the modified header to prevent caching, you also need to tell the server that the content type is application/x-www-form-urlencoded; then you transmit the length of all the request parameters as the value to accompany Content-length. You also need to tell the server read more..

  • Page - 355

    330 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX The retrieved() method doesn’t differ much from the other examples. Undo what you have done 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 - 356

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 331 You can also use the Ajax approach in an unobtrusive and optional manner to make older effects more eye-catching and targeted better to those who want them. In the previous chapter, you developed a dynamic navigation that collapsed and expanded nested links, and I promised you that we’d come back to that read more..

  • Page - 357

    332 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX <ul> <li><a href="training.php">Employee Training</a></li> <li><a href="audits.php">Auditing</a></li> <li><a href="bulkmail.php">Bulk sending/email campaigns</a></li> </ul> </li> <li><a read more..

  • Page - 358

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 333 For a top-level item like that corresponding to the products page, the code will be even less: <ul id="nav"> <li><a href="index.php">Home</a></li> <li><strong>Products</strong></li> <li><a href="services.php">Services</a></li> read more..

  • Page - 359

    334 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX You can now use JavaScript to offer the user a more advanced navigation menu that shows the complete site map and loads the content via XHR instead of reloading the whole page. To achieve this, you can reuse the dynamic navigation script developed in the previous chapter and add one line that triggers read more..

  • Page - 360

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 335 XHRSiteNav.js Xhrsitenav = { navID : 'nav', trigger : null, triggerID : 'AJAXtrigger', triggerLabel : 'Switch to advanced navigation', downLabel : 'Switch to basic navigation', output : 'content', loadingMessage : '<img src="../indicator_big.gif" ➥ alt="loading..." />', The read more..

  • Page - 361

    336 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX You then take the link inside the trigger and remove anything after and including the ques- tion mark. This means that if the user clicks the link, it’ll turn off both the Ajax and the dynamic menu functionality. You also change the link text to the label text for the basic navigation. XHRSiteNav.js read more..

  • Page - 362

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 337 XHRSiteNav.js (continued) var request; try { request = new XMLHttpRequest(); } catch(error) { try { request = new ActiveXObject('Microsoft.XMLHTTP'); } catch(error) { return true; } } read more..

  • Page - 363

    338 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX The createTrigger() method checks whether there is already a trigger defined and cre- ates a new one if necessary. The trigger is the list item containing the link that allows the user to switch between the different navigation states. There shouldn’t be any surprises in this method—it could have been part read more..

  • Page - 364

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 339 XHRSiteNav.js (continued) var shorturl = xhrsitenav.shorturl( o.getAttribute( 'href' ) ); var st = document.createElement( 'strong' ); st.className = shorturl.replace( '.php', '' ); st.innerHTML = o.innerHTML; o.parentNode.replaceChild( st, o ); var url = 'content/' + read more..

  • Page - 365

    340 CH APTER 8 ■ BACK -END INTERACTION WITH AJAX This is an example of how you can make high-end JavaScript functionality optional instead of hoping that visitors can deal with it. It is not a very common approach, as it adds an extra level of complexity to the interface; but depending on the audience of your product, it read more..

  • Page - 366

    CHA P TER 8 ■ BACK- END INTERACTIO N WITH A J AX 341 • moofx (http://moofx.mad4milk.net/) was especially developed with size in mind. The entire library is only 3KB and offers lots of visual tricks and effects, along with a basic Ajax engine. • Rico (http://openrico.org/rico/home.page) was developed with web applications in mind and features a panel bar, read more..

  • Page - 367

    read more..

  • Page - 368

    343 ■ ■ ■ 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. I’ll start with a quick introduction read more..

  • Page - 369

    344 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S On the other hand, validating with JavaScript has several issues: • It cannot be trusted as the one and only means of validation (JavaScript could not be available or could even be deliberately turned off to circumvent your validation measures). • It promotes the notion that validating input is read more..

  • Page - 370

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 345 The one and only cracking skill needed to work around this protection is to look at the page source, or—if the protection is in its own JavaScript file—open that in a browser or text editor. In some cases, where there is no redirection to the correct page, but only to the wrong one, simply turning read more..

  • Page - 371

    346 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S The biggest mistake a lot of client-side validation tutorials and ready-made solutions make is not considering localization. • My birthday in American notation is 4/26/1975, in Europe 26/04/1975; others might write it as 26. April 1975 or Apr. 26, 1975. • Numbers are displayed as 1,000.95 in read more..

  • Page - 372

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 347 • substr(start,n): Returns the string that is n characters long beginning at start. • substring(start,end): Returns the part of the string in between start and end. The other, more powerful, string methods, search, replace, and match, work with regular expressions. I will talk about those shortly. You can read more..

  • Page - 373

    348 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S Let’s go through the script and see what is going on there. exampleCheckNumberString.html function isNumber () { var currentCode; var total = document.getElementById( 'total' ); if( !total ){ return false; } total = total.value; You define a variable called currentCode and get the value of read more..

  • Page - 374

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 349 exampleCheckNumberString.html (continued) for( var i = 0; i < t otal.length; i++ ) { currentCode = total.charCodeAt( i ); if( currentCode != 45 && currentCode != 46 && currentCode < 48 || currentCode > 57 ) { alert( 'Only Numbers are allowed' ); read more..

  • Page - 375

    350 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S exampleCheckEmailString.html (continued) if( mailstring.indexOf( '@' ) == -1 ) { error = 'This email has no @ sign'; alert( error ); return false; } else if( mailstring.lastIndexOf( '@' ) != mailstring. ➥ indexOf( '@' ) ) { read more..

  • Page - 376

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 351 Display an error and stop the form from submitting if the email is invalid. exampleCheckEmailString.html (continued) if( !checkValidCharacters( n ) ) { error = 'The email name contains invalid characters'; alert( error ); return false; } The name may only contain numbers, letters, read more..

  • Page - 377

    352 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S exampleCheckEmailString.html (continued) function checkValidCharacters( n ) { for( var i = 0; i < n .length; i++ ) { currentCode = n.charCodeAt( i ); if( currentCode == 45 || currentCode == 46 || currentCode == 95 || ( currentCode > 96 read more..

  • Page - 378

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 353 exampleCheckNumberMath.html (excerpt) function isNumber() { var total = document.getElementById( 'total' ); if( !total ){ return false; } total = total.value; if( total.length == 0 ) { alert( 'Field is empty' ); return false; } if( isNaN( total ) ) { alert( 'Please read more..

  • Page - 379

    354 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S exampleCheckDateMath.html (continued) if( datestring.length != 10 && datestring.indexOf( '/' )== -1 || datestring.indexOf( '/' ) != 2 || datestring.lastIndexOf( '/' ) != 5){ alert( 'The date is not in the format dd/mm/yyyy' ); return false; } You read more..

  • Page - 380

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 355 exampleCheckDateMath.html (continued) if( (year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0) ) { leap = 1; } if( (month == 2) && (leap == 1) && (day > 29) ) { alert( 'This month does not have that many days' ); return false; } read more..

  • Page - 381

    356 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S exampleCheckDateObj.html (excerpt) function isValidDate() { var datestring = document.getElementById( 'date' ); if( !datestring ){ return false; } datestring = datestring.value; if( datestring.length == 0 ) { alert( 'Field is empty' ); return false; } if( datestring.length read more..

  • Page - 382

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 357 ■Tip Get yourself well acquainted with the JavaScript Math and Date objects. A lot of times you don’t have to come up with clever code yourself, but you can piggyback on functionality they already provide you with. Regular Expressions Regular expressions help you match a string against a character pattern read more..

  • Page - 383

    358 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S This would find polecat or wildcat: var searchTerm = /cat$/; var searchTerm = new RegExp('cat$' ); If you want to find “cat” regardless of case—for example, to match “cat”, “Catherine”, or “CAT”—you need to use the i attribute following the second slash. This causes the case to be read more..

  • Page - 384

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 359 If you want, for example, to find any word all in lowercase, followed immediately by a word in uppercase, you’ll use var searchTerm = /[a-z][A-Z]/g; var searchTerm = new RegExp( '[a-z][A-Z]', 'g' ); You can use the ^ character inside the brackets to exclude an option from the search. If you wanted to avoid read more..

  • Page - 385

    360 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S ■Note Notice that you need to escape characters that are to be used literally, and not with any special meaning they might have in a regular expression pattern, like the dash in this case. You can do this by pre- ceding the character with a backslash, \. Characters that need read more..

  • Page - 386

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 361 to escape them! With this knowledge, you should be well equipped to write your own regular expressions. As proof, let’s go back to the example in the beginning paragraph of this section: var validEmail = /^[\w]+(\.[\w]+)*@([\w]+\.)+[a-z]{2,7}$/i E-mails can be pretty straightforward, like me@example.com, or more read more..

  • Page - 387

    362 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S For example, if you have a list of names in the format Surname, Name and you want to convert each entry in the list into Name Surname format, you can do the following: exampleNameOrder.html names=[ 'Reznor, Trent', 'Eldritch, Andrew', 'Clark, Anne', 'Almond,Marc' ]; for( i = 0; i read more..

  • Page - 388

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 363 Regular Expression Resources As with any programming language, there are dozens of ways to reach the same goal, and I don’t want to just give examples to copy and paste when getting your head around regular expressions will get you so much further. There are many online resources that list patterns according to read more..

  • Page - 389

    364 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S Form Validation Techniques We’ll now talk about some of the techniques you can use with forms, spotting which fields need validation and how to tell the user that something is amiss. The list of examples is by far not complete—newer technologies, better browsers, and behavior patterns of users change read more..

  • Page - 390

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 365 hiddenFieldForm.js (excerpt) init:function() { [... code snipped ...] var mandatory = document.getElementById('mandatory'); if( !mandatory ){ return; } hfv.mandatory = mandatory.value.split( ',' ); [... code snipped ...] }, send:function(e) { [... code snipped ...] for( var i = 0; i < h read more..

  • Page - 391

    366 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S asteriskForm.js (excerpt) init:function() { hfv.mandatory = []; [... code snipped ...] hfv.f = document.getElementsByTagName( 'form' )[0]; var msgs = hfv.f.getElementsByTagName( 'span' ); for( var i = 0; i < m sgs.length; i++) { if( DOMhelp.cssjs( 'check', msgs[i], 'mandatory' ) ) { read more..

  • Page - 392

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 367 www.alistapart.com/articles/scripttriggers/) in February 2005. We won’t go into an exam- ple here, but what it means is that you come up with nonstandard attributes for elements like <input type="text" name="name" id="name" required="true" /> You can then use getAttribute() in your script read more..

  • Page - 393

    368 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S You can retrieve all the mandatory elements by looping through the JSON object: for( i in validationRules ) { // i will be Name, subject, Message, email if( !document.getElementById( i ) ) { continue; } toplist.checkValue( i ); } Retrieving the patterns and error messages is as read more..

  • Page - 394

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 369 } else { echo '\'' . $b . '\' : \'' . $validationRules[$a][$b]. ➥ '\',' . "\n"; } } echo '},' . "\n"; } echo '};'; } ?> Don’t worry read more..

  • Page - 395

    370 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S Figure 9-1. Showing a list of erroneous fields above the Submit button You start by embedding the rule set in the head of the HTML: exampleTopList.html (excerpt) <script type="text/javascript" src="validationRules.php?json=1"></script> You should plan your script starting with the skeleton of read more..

  • Page - 396

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 371 remove older error messages (as the user will not reload the page but may enter data several times because the script stops the page from reloading when there is an error), and a tool method to check the value of each mandatory form field. I’ll now go through the script step by step and explain what read more..

  • Page - 397

    372 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S The utility method checkValue() adds new elements to the error array if there are prob- lems with some of the fields, which is why you check whether its length is larger than 0 before you start assembling the error message. Next, create a DIV, store it in the errorMessage property, and read more..

  • Page - 398

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 373 toplist.js (continued) checkValue : function( o ) { var elm = document.getElementById( o ); switch( elm.type ) { case 'text' : if( !validationRules[o][ 'pattern' ].test( elm.value ) ) { toplist.error.push( validationRules[o][ 'error' ] ); read more..

  • Page - 399

    374 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S In the case of the select box—which in this example is a single select box, therefore the type is select-one—you need to retrieve the value of the selected option via the options array and the selectedIndex property. As the form offers an “other” option, yo u need to check whether it was read more..

  • Page - 400

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 375 hideform.js (continued) send:function( e ) { toplist.flushErrors(); for( var i in toplist.validationRules ) { [... code snipped ...] } if( toplist.error.length > 0 ) { [... code snipped ...] read more..

  • Page - 401

    376 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S The flushErrors() message now needs to set the display property of the form back to block, and indicate that all the changes are necessary and the rest of the script stays as it was. Highlighting Erroneous Fields Individually Especially with larger forms, it makes a lot more sense to display error read more..

  • Page - 402

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 377 The properties and the init() method stay the same as in the toplist example. errorFields.js (continued) send:function( e ) { ef.flushErrors(); for( var i in validationRules ) { if( !document.getElementById( i ) ) { continue; } ef.checkValue( i ); } read more..

  • Page - 403

    378 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S if( !validationRules[o]['pattern'].test( curelm ) ) { ef.error.push( validationRules[o][ 'error' ] ); ef.addErrorMsg( elm, validationRules[o]['error'] ); } break; } }, The changes in the checkValue() method are read more..

  • Page - 404

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 379 These changes mean that there is no single new element showing the errors but one at each erroneous field. This means that the flushErrors() method needs to loop through all mandatory fields and check whether there is a previous sibling node that is a SPAN and has the right class applied to it. If all read more..

  • Page - 405

    380 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S dynamicFields.js (continued) sendField : function( e ) { var t = DOMhelp.getTarget( e ); if( t.previousSibling && t.previousSibling.nodeName.toLowerCase() == 'span' && t.previousSibling.className == df.errorClass ) { read more..

  • Page - 406

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 381 Other Dynamic Validation Methods It is very tempting to make every field validate immediately when the user changes it, and you can do a lot with Ajax and the proper back-end datasets or functionality. One great example is to include suggestions of what data is valid while you enter a form. Google read more..

  • Page - 407

    382 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S The XML data is very simple: contacts.xml <?xml version="1.0" encoding="utf -8"?> <contacts> <name>Bill Gates</name> <name>Linus Torvalds</name> <name>Douglas Coupland</name> <name>Ridley Scott</name> <name>George Lucas</name> <name>Dan read more..

  • Page - 408

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 383 contactSuggest.js (continued) check : function( e ) { if( window.event ) { var key = window.event.keyCode; } else if( e ) { var key = e.keyCode; } if( key == 8 ) { return; } if( key == 40 ) { cs.f.value = read more..

  • Page - 409

    384 CH APTER 9 ■ D A TA VALIDA TION T E CH NIQ U E S } else { cs.failed( request ); } } } request.setRequestHeader( 'If-Modified-Since', ➥ 'Wed, 05 Apr 2006 00:00:00 GMT' ); request.send( null ); read more..

  • Page - 410

    CH APTER 9 ■ D A TA VALIDA TION TECH NIQUES 385 If there is an error, the user is informed via an alert. When the window has finished loading the document, the method cs.init() is called. For a small number of contacts, using XHR is probably not worth the effort, and you’d be better off importing the data in JSON format and spare yourself the read more..

  • Page - 411

    read more..

  • Page - 412

    387 ■ ■ ■ 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 techniques of static galleries and how to enhance them and move on to a gallery that uses PHP and Ajax to pull images dynamically from the server. ■Note read more..

  • Page - 413

    388 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY What Is a Thumbnail Gallery and What Should It Do? The idea of a thumbnail gallery goes back to the times when browsers started to support images, and connection speeds on the Web could be measured in the single kilobits. The job of such a gallery was and still is to read more..

  • Page - 414

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 389 If there are a lot of images, the thumbnail pages may be paginated, showing a certain num- ber of thumbnails at a time and offering navigation forward and backward through the whole collection. With purely static galleries, this means you have to generate all read more..

  • Page - 415

    390 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY You can test the effect by opening the demo exampleFakeDynamic.html. Let’s go through the functionality step by step, starting with a skeleton for the script: fakeDynamic.js (skeleton) fakegal = { // IDs thumbsListID : 'thumbs', largeContainerID : 'photo', // CSS classes read more..

  • Page - 416

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 391 In terms of methods, you need • A method to initialize the functionality • A utility method that initially creates the image container • A method to show the picture • A method to set the picture to be shown • A method to navigate to the next read more..

  • Page - 417

    392 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY The init() method tests whether DOM is supported and retrieves the element that con- tains the thumbnails. It then loops through all the links after storing the number of all links in a property called all (this is necessary later on to avoid a next link on the read more..

  • Page - 418

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 393 fakeDynamic.js (continued) fakegal.next = DOMhelp.createLink( '#', '' ); fakegal.next.innerHTML = fakegal.nextContent; fakegal.next.className = fakegal.nextClass; DOMhelp.addEvent( fakegal.next, 'click', fakegal.navPic, false ); fakegal.next.onclick = read more..

  • Page - 419

    394 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY fakeDynamic.js (continued) setPic : function( pic ) { var a; var picLink = fakegal.c.getElementsByTagName('a')[1]; picLink.innerHTML = ''; The setPic() method takes the second link inside the image container (which is the link after the closing link) and read more..

  • Page - 420

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 395 Test to see whether the current property of the main object is equal to 0, and hide the pre- vious picture link if this is the case. Do the same with the next picture link and compare current with the number of all thumbnails (stored in all). Hide or show read more..

  • Page - 421

    396 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY Figure 10-1. Using JavaScript to simulate a server-controlled dynamic image gallery 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 read more..

  • Page - 422

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 397 exampleFakeDynamicAlt.html (excerpt) <ul id="thumbs"> <li> <a href="galleries/animals/dog2.jpg"> <img src="galleries/animals/tn_dog2.jpg" title="This squar e is mine" alt="Dog in a shady square" read more..

  • Page - 423

    398 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY The first change is a cosmetic one: you add a new CSS class that will be applied to the caption. fakeDynamicAlt.js (continued) init : function() { if( !document.getElementById || !document.createTextNode ) { return; } fakegal.tlist = read more..

  • Page - 424

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 399 The init() method remains unchanged, but the showPic() method needs to read the alternative text and the title attribute of the image, in addition to the href attribute of the link, and send all three of them as parameters to setPic(). fakeDynamicAlt.js read more..

  • Page - 425

    400 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY 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; read more..

  • Page - 426

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 401 fakegal.next = DOMhelp.createLink( '#', '' ); fakegal.next.innerHTML = fakegal.nextContent; fakegal.next.className = fakegal.nextClass; DOMhelp.addEvent( fakegal.next, 'click', fakegal.navPic, false ); fakegal.next.onclick = DOMhelp.safariClickFix; read more..

  • Page - 427

    402 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY 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 may not want to reload the whole page every time the user read more..

  • Page - 428

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 403 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 read more..

  • Page - 429

    404 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY dyngal_xhr.js (continued) assignHandlers : function( o ) { if( !document.getElementById( o ) ){ return; } o = document.getElementById( o ); var gLinks = o.getElementsByTagName( 'a' ); for(var i = 0; i < gLinks.length; i++ ) { read more..

  • Page - 430

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 405 } } request.open( 'get', url, true ); request.onreadystatechange = function() { if( request.readyState == 1 ) { container.innerHTML = 'Loading...'; } if( request.readyState == 4 ) read more..

  • Page - 431

    406 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY Creating an Image Badge from a Folder Let’s have a go at another small gallery example using PHP and JavaScript/XHR before we look at some ready-made third-party code and online services in the next chapter. If you already use Flickr (http://www.flickr.com) or you read blogs a read more..

  • Page - 432

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 407 Figure 10-4. Two image folders as badge galleries 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 read more..

  • Page - 433

    408 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY ■Note The following is a quick explanation of the PHP script. This is not JavaScript, but I hope you appre- ciate some insight into the workings of the tools the upcoming badge script uses. badge.php <?php $c = preg_match( '/\d+/', $_GET['c'] ) ? $_GET['c'] : 5; $s read more..

  • Page - 434

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 409 You use the array_slice() method of PHP to reduce the array down to the chosen images ($c images starting at $s) and test whether $s is larger than 0. If it is, write out a list element with the class badgeprev that has the right parameters in the read more..

  • Page - 435

    410 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY badge.js (continued) init : function() { var newUL, parent, dir, loc; if( !document.getElementById || !document.createTextNode ) { return; } var links = document.getElementsByTagName( 'a' ); for( var i = 0; i < links.length; read more..

  • Page - 436

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 411 (you loop through all the links of the document, which means that when you remove one of them, the counter needs to decrease to stop the loop from skipping the following link). badge.js (continued) badge.container = document.createElement( 'div' ); read more..

  • Page - 437

    412 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY failed : function( requester ) { alert('The XMLHttpRequest failed. Status: ' + requester.status); return true; }, The Ajax/XHR methods remain largely unchanged, the only difference being that when the data is successfully retrieved, the assignHandlers() method is read more..

  • Page - 438

    CH A P T E R 1 0 ■ MODE RN JAVAS CRIPT CASE STUDY : A D Y NAMIC GALLE RY 413 The load method retrieves the event target and makes sure it is a link. It retrieves the href attribute value of the event target and cleans it up before calling the doxhr method with the element stored in the link’s parent property as the output read more..

  • Page - 439

    414 CH APTER 1 0 ■ MODE RN JAVASC RIPT CASE STUD Y : A DY NA MIC GALLERY badge.js (continued) var source = t.getAttribute( 'href' ); var newImg = document.createElement( 'img' ); badge.deletePic(); newImg.setAttribute( 'src', source ); badge.container.appendChild( newImg ); DOMhelp.addEvent( badge.container, 'click', read more..

  • Page - 440

    415 ■ ■ ■ CHAPTER 11 Using Third-Party JavaScript As you’ll have 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 read more..

  • Page - 441

    416 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT different), and you attract a lot of talent that you may want to hire at a later stage. With a devel- oper network, you see immediately what a person can do instead of having to rely on his CV. As a developer, this means that if you take a look around the Web, you find an amazing amount of read more..

  • Page - 442

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 417 RSS Feeds and REST APIs I’ve covered RSS feeds in Chapter 8 already, but it is worth mentioning them again here, as it is amazing what kind of information you can find on the Web for you to use: • There are hardly any news agencies that don’t offer RSS feeds of the latest happenings. read more..

  • Page - 443

    418 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT The API also allows for other parameters like the start of the search result section you want to see or the output format. For example, if you want the results 10 to 15 for the search term “web- standards” in JSON format, you can have that: http://api.search.yahoo.com/WebSearchService/ read more..

  • Page - 444

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 419 The BBC currently offers a prototype of a REST API at http://www0.rdthdo.bbc.co.uk/ services/api/ that will be part of their other developer offers at http://backstage.bbc.co.uk/ once it has matured enough. This API allows you to browse the BBC program schedule in RSS format. BBC has an Ajax example read more..

  • Page - 445

    420 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT ■Note XPath is a W3C standard language to reach parts of an XML document, normally used in connection with XSLT or XPOINTER (http://www.w3.org/TR/xpath). As modern HTML should conform to XML syntax rules (all tags closed, all elements lowercase, attribute values in quotation marks, and single attributes read more..

  • Page - 446

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 421 Figure 11-1. Showing and hiding code examples with jQuery jqueryTest.js $( document ) . ready ( function() { $( 'pre' ).before( '<p><a class="trigger" ➥ href="#">Show code</a></p>' ); $( 'pre' ).hide(); $('a.trigger').toggle ( read more..

  • Page - 447

    422 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT As you may remember, we talked in Chapter 5 about the ugly effect of the page content show- ing up before you can hide it. This method works around that problem. jqueryTest.js (continued) $( 'pre' ).before( '<p><a class="trigger" ➥ href="#">Show code</a></p>' ); read more..

  • Page - 448

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 423 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 read more..

  • Page - 449

    424 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT ) function parseCode(o){ if(!o.nextSibling.hascode){ $.get (o.href, function(code){ code=code.replace(/&/mg,'&#38;'); code=code.replace(/</mg,'&#60;'); read more..

  • Page - 450

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 425 You use one of jQuery’s iterator methods, each(), to loop through all links that have the CSS class codeExample. You then create PRE elements with the class codeExample and embedded CODE elements after each of these links via the after() method and the $(this) selector before hiding all PRE read more..

  • Page - 451

    426 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT jqueryTestAjax.js (continued) code=code.replace( /&/mg, '&#38;' ); code=code.replace( /</mg, '&# 60;' ); code=code.replace( />/mg, '&# 62;' ); code=code.replace( /\"/mg, '&#34;' ); read more..

  • Page - 452

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 427 the development process quicker and easier, not make us dependent on them or repeat mis- takes we’ve done with libraries in the past already—creating applications and web sites that don’t work without JavaScript. Next we’ll look at using the Google Maps API to create mapping applications. Using an read more..

  • Page - 453

    428 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT The result is Address 5555 Melrose Ave Los Angeles CA 90038 Latitude 34.083517 ° N 34 ° 5' 0.7" Longitude -118.321951 ° W 118 ° 19' 1 9.0" An even easier solution is to use the REST APIs at http://www.localsearchmaps.com (explained at http://emad.fano.us/blog/?p=277) and http://www.zeesource.net/maps/ geocoding.do. The read more..

  • Page - 454

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 429 Make sure that you give that element dimensions in the CSS, as otherwise the map will behave erratically. googleMaps.css #map{ width:400px; height:300px; border:1px solid #999; margin:1em; } To add the map to your HTML document, embed the following script (either inline or in a SCRIPT element) read more..

  • Page - 455

    430 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT You add the map by calling the GMap2() method, which creates a new map object. The method takes the element to insert the map into as the parameter, in this case the element with the ID map. You can add as many maps as you want to a document. You define a new point with the GLatLng() method that read more..

  • Page - 456

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 431 around and the + and – buttons to zoom in and out. The GMapTypeControl() creates the three buttons to show the map, a satellite photo, or a hybrid—which means a satellite photo with road names. The GScaleControl() displays the scale of the map on the bottom left next to the read more..

  • Page - 457

    432 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT The API creates the overview control element as a <div> with the ID map_overview. It does that with any map; if the map has the ID myMap, the ID of the overview control would be myMap_overview. You can use this information to position the control absolutely and the main map DIV relatively, and read more..

  • Page - 458

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 433 addEvent() does. In the function that adds the message, you create a new text node of the doc- ument and use the openInfoWindow() method of the map with the point and the new text node as parameters to display the information window as shown in Figure 11-5. exampleGoogleMapsMarkerEvent.js function read more..

  • Page - 459

    434 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT Another really cool option of Google maps is that you can set the zoom level with the setZoom() method, and you can move the map center to another location by using the panTo() method. Furthermore, the openInfoWindowHtml() method allows you to define a function to call when the user closes the read more..

  • Page - 460

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 435 GEvent.addListener( homeMarker, 'click', addMessage ); } } window.onload = addMap; window.onunload = GUnload; The result is shown in Figure 11-6. Figure 11-6. Panning from one map location to a different one The example needs to zoom out one level to pan smoothly to the other location. If the read more..

  • Page - 461

    436 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT googleMapsPan.js (continued) var home = new GLatLng( 51.5623, -0.0934 ); var work = new GLatLng( 51.5138, -0.1284 ); var homeMarker = new GMarker( home ); var workMarker = new GMarker( work ); var homeMessage = 'This is where Chris lives'; var workMessage = read more..

  • Page - 462

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 437 googleMapsPan.js (continued) function goToWork() { map.setZoom( 12 ); map.panTo( work ) map.openInfoWindowHtml( work, workMessage, { onCloseFn : backToHome } ); } function backToHome(){ read more..

  • Page - 463

    438 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT Full Service: The Yahoo Developer Network and User Interface Library Yahoo, being one of the oldest Internet content and service providers, has taken an interesting step by offering the Yahoo Developer Network to web developers. The network homepage is http://developer.yahoo.com, and there you can find a listing of read more..

  • Page - 464

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 439 Bouncy Headlines Using YUI Let’s use the YUI and its components to create a fancier example of clickable headlines. The demo exampleBouncyHeadlines.html uses the DOM, the Event, and the Animation components to show and hide the content below the headlines in an animation when the user clicks the read more..

  • Page - 465

    440 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT }, toggle : function() { var attributes, anim; var c = this.content; if( c.shown ) { attributes = { height: { from : c.defaultHeight, to : 0}, opacity: { from : 1, to : 0 } }; anim = new read more..

  • Page - 466

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 441 bouncyHeadlines.js (excerpt) YAHOO.namespace('bh'); bh = { triggerClass:'show', You start the initialization method init() by defining the variables listitems, i, and content and store the element with the ID headlines in the property headings of the main object bh. If there is no element with read more..

  • Page - 467

    442 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT headline that was clicked, and you store the paragraph in a property called content. You read out the property shown of the paragraph—which will indicate whether the paragraph is visible or not—and if the property is not set, you add the CSS class shown to the paragraph to make it visible. Adding and read more..

  • Page - 468

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 443 To show the paragraph, you can use backOut to make it appear smoothly, show some extra pixel lines below it, and snap back to the right height until the real value is reached. You start the animation by invoking the animate() method of the animation object (in this case anim). The anim read more..

  • Page - 469

    444 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT The last thing your script needs is a method that initially hides all the paragraphs and calls the init() method. You hide the paragraphs by adding a new CSS class to the headlines ele- ment using addClass(). bouncyHeadlines.js (continued) hideContents : function() { YAHOO.util.Dom.addClass( 'headlines', read more..

  • Page - 470

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 445 The following short example loads the file demotext.html when the window has finished loading: exampleXUIAjax.html (excerpt) var handlers = { success: success, failure: failure } function success( t ) { alert( t.responseText ); } function failure( t ) { alert( 'There was an error: ' + read more..

  • Page - 471

    446 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT Let’s take both library components and some DOM trickery to simulate a browser pop-up window that resides in the same document, loads and displays a document via Ajax, and allows the user to move it around and close it. Figure 11-8 shows the result. Figure 11-8. Simulating a pop-up window with YUI library read more..

  • Page - 472

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 447 <body> <a href="demotext.html" onclick="makeRequest(this);return false " >Load Dem o Text</a> <div id="win"> <div class="hd"></div> <div class="bd"></div> </div> </body> </html> Notice that this example is read more..

  • Page - 473

    448 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT to drag the panel outside the currently visible browser section or not. Setting it to true ensures that there won’t be any ugly scrollbars when the user drags the panel too far to the right or down. The Panel() method automatically allows the user to drag the panel around when you set draggable to read more..

  • Page - 474

    CHAPTER 11 ■ USI N G TH IRD- P A RT Y JAVAS CRIP T 449 windowbody.innerHTML=content; var title = win.getElementsByTagName( 'title' )[0].innerHTML; var body = document.getElementById( 'popupbody' ).innerHTML; You set the panel’s body and header content using the setBody() and setHeader() meth- ods (the former conveniently overrides the rest of the read more..

  • Page - 475

    450 CH APTER 1 1 ■ US ING THIRD-PARTY JA VASCRIPT Summary I hope this chapter has given you a taste of what is out there at the moment, and I am sure that this is simply the beginning of a longer experience of shared content, information, and ser- vices. Many developers spend a lot of time creating wonderful code just to realize that there is read more..

  • Page - 476

    451 ■ ■ ■ APPENDIX 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, as 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 read more..

  • Page - 477

    452 APPENDIX ■ DE B UGGI NG JA VASCRIPT Trying to Access Undefined Variables We talked about it in the first 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). Stewie = "Son of Peter and Lois"; var Chris = "Older Son of read more..

  • Page - 478

    APPENDIX ■ DEBU GGING JAVASCRI PT 453 } else { var str = father + ' ' + mother + ' ' + child; out.appendChild( document.createTextNode( str ) ); } } getFamilyData( 'tree', true, 'Griffin' ); Microsoft Internet Explorer tells you that there is an error in line 23—“‘outputID’ is unde- fined,” as shown in Figure A-1. Figure read more..

  • Page - 479

    454 APPENDIX ■ DE B UGGI NG JA VASCRIPT Figure A-3. The misspelled function parameter that caused the error Typos in parameters are a very confusing bug, as 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 very common mistake is not closing read more..

  • Page - 480

    APPENDIX ■ DEBU GGING JAVASCRI PT 455 out.appendChild( newUL ); } } getFamilyData( 'tree', true, 'Griffin' ); The orphan closing brace shown in bold will cause a “syntax error in line 30.” The same problem occurs when you don’t close all the braces in a construct, a mistake that can easily happen when you don’t indent your code: read more..

  • Page - 481

    456 APPENDIX ■ DE B UGGI NG JA VASCRIPT The previously missing curly brace is shown in bold (following the “is in the range” alert() message). Not closing or closing too many parentheses is another common problem. This happens when you nest functions in if() conditions and later on delete some of them. For example: if (all = read more..

  • Page - 482

    APPENDIX ■ DEBU GGING JAVASCRI PT 457 The preceding lacks one addition sign before the child variable: father = "Peter"; mother = "Lois"; child = "Chris"; family = father+" "+mot her+" "+child; Another obstacle is to make sure you don’t concatenate the wrong data types. father = "Peter"; fAge = 40; mother = "Lois"; mAge read more..

  • Page - 483

    458 APPENDIX ■ DE B UGGI NG JA VASCRIPT 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 will entice Brian to hear all the time, not only when Stewie has read more..

  • Page - 484

    APPENDIX ■ DEBU GGING JAVASCRI PT 459 padding:1em; } html>body #DO Mhelpdebug{ position:fixed; min-height:200px; height:200px; overflow:auto; } exampleDebugTest.html (excerpt) <script type="text/javascript" src="../DOMhelp.js"></script> <script type="text/javascript"> function DOMDebugTest(){ DOMhelp.initDebug(); for(var i = 0; i read more..

  • Page - 485

    460 APPENDIX ■ DE B UGGI NG JA VASCRIPT The catch() method retrieves an Exception object as a parameter when an error occurs inside the try statement. You can give this object any variable name; in this example we call it exceptionObject. Depending on the error and the browser, this object will have different properties, and the properties that are the read more..

  • Page - 486

    APPENDIX ■ DEBU GGING JAVASCRI PT 461 exampleTryCatchTypo.js try{ allert( 'this is a code example' ); } catch( exceptionObject ) { var errorString = ''; for( i in exceptionObject ) { errorString += i + ':' + exceptionObject[i] + '\n'; } alert( errorString ); } The results on MSIE 6 are the following: name:TypeError message:Object expected read more..

  • Page - 487

    462 APPENDIX ■ DE B UGGI NG JA VASCRIPT Using try and catch in a debugging process can be very helpful, and depending on the browser, you can easily spot the problem. ■Note Notice that Opera reports the line number of the code inside the SCRIPT element, while Firefox reports the line number of the whole HTML document. MSIE leaves you in read more..

  • Page - 488

    APPENDIX ■ DEBU GGING JAVASCRI PT 463 Error Reporting in Browsers Browsers help you to different degrees to debug your code. Following is a roundup of different browsers and their means of displaying errors and locating their origin. As I wanted to give an overview of different browsers you can use, I will not go into much further detail about the dif- ferent read more..

  • Page - 489

    464 APPENDIX ■ DE B UGGI NG JA VASCRIPT As the error messages provided by MSIE can be rather cryptic, like “Object does not sup- port this method or property,” and if MSIE is your only option for development, you might want to download the free Microsoft script debugger at http://www.microsoft.com/downloads/ read more..

  • Page - 490

    APPENDIX ■ DEBU GGING JAVASCRI PT 465 Figure A-5. The debugging menu of Safari Figure A-6. Enabling the debugging menu with Safari Enhancer read more..

  • Page - 491

    466 APPENDIX ■ DE B UGGI NG JA VASCRIPT Opera 8.5 Opera not only comes with options to quickly turn off all kinds of browser support (JavaScript, cookies, plug-ins, pop-ups) by pressing F12, which helps immensely to test whether your web page is dependent on JavaScript or not, it also has a built-in JavaScript console that gives very detailed error reports. read more..

  • Page - 492

    APPENDIX ■ DEBU GGING JAVASCRI PT 467 ■Note Don’t be confused if your Firefox browser doesn’t have the same options as shown in Figure A-8; some of them are dependent on extensions I installed. However, you should have the JavaScript console. Figure A-8. Showing the JavaScript console in Firefox Once activated, the JavaScript console is visible in its read more..

  • Page - 493

    468 APPENDIX ■ DE B UGGI NG JA VASCRIPT By default, the JavaScript console will open in a new window, but there is a trick you can use to show it in the sidebar instead. 1. Make sure the bookmarks toolbar is visible by selecting View ➤ Toolbars ➤ Bookmarks Toolbar. 2. Right-click the toolbar and select New Bookmark. 3. Add the information read more..

  • Page - 494

    APPENDIX ■ DEBU GGING JAVASCRI PT 469 Developers keep churning out new extensions and putting them on the Web. Two of those are very handy for you as a JavaScript developer: The Web Developer Extension The Web Developer extension is a toolbar by Chris Pederick that is available at http:// www.chrispederick.com/work/webdeveloper/. This toolbar allows you to quickly read more..

  • Page - 495

    470 APPENDIX ■ DE B UGGI NG JA VASCRIPT Venkman Mozilla’s answer to the Microsoft Script Debugger is called Venkman and is available at https:// addons.mozilla.org/firefox/216/. Venkman is a full debugging suite that allows you to watch variables, set debugging points, and really go down into the depths of JavaScript development. Explaining all the features of Venkman read more..

  • Page - 496

    471 Index ■Special Characters #text nodes, 89 $1 variable, 362 $(document).ready ( ) method, 421 $.get( ) method, 425 % operator, 21 && operat or, 48 * operator, 21 */ syntax, JavaScript, 8 /* syntax, JavaScript, 8 // syntax, JavaScript, 8 \\ escape sequence, 20 || operator, 48 + operator, 21, 23 ++ operator, 21 != operator, 46 == operator, 46 > operator, 46 read more..

  • Page - 497

    472 ■INDEX asynchronously, 300 attachEvent( ) method, 166 attributes of elements changing, 107–108 reading, 117 ■B \b escape sequence, 20 back( ) method, 230, 246 background image, 192 background-position property, 191 before( ) method, 422 behavior layer, JavaScript as object detection vs. browser dependence, 65–68 overview, 63–65 progressive enhancement, 68–69 block property, 261 read more..

  • Page - 498

    473 ■INDEX Find it faste r at http://superind ex.apr ess.com checked property, 275, 279–281, 283–284, 294 childNodes property, 100 children, 99–100 Clark, Chris, 139 click( ) method, 276 click event, 163, 247, 249, 257, 259, 294 click event handler, 335 client-side validation, pros and cons of, 343–344 close( ) method, 215, 220 closestSibling( ) method, 120, 125, 178, 203, 294 read more..

  • Page - 499

    474 ■INDEX debugging (continued) sequential uncommenting, 462 tracing errors with alert( ) and console elements, 458–459 decision making comparing data, 46–48 conditional statements breaking out of branch or loop, 52 overview, 49–52 logical operators, 48 loops continuing, 58–59 for loop, 54–56 overview, 54 while loop, 56–58 overview, 45 switch statement, 52–54 testing multiple values, read more..

  • Page - 500

    475 ■INDEX Find it faste r at http://superind ex.apr ess.com radio buttons, 281–284 select boxes, 286–291 text fields, text areas, hidden and password fields, 278–279 using blur( ) and focus( ), 278 reading element attributes, node values, other node data, 117 elements collection, 276–277, 288 else condition, 281 else statement, 9, 15 <embed> tag, 153 embedded slide shows, read more..

  • Page - 501

    476 ■INDEX form property, 275, 277 form validation techniques CSS classes method, 366 custom attribute method, 366–367 designating mandatory fields, 364 failures of these methods, 367 hidden field method, 364–365 indicator element method, 365–366 overview, 364 sharing validation rules, 367–369 formmail.pl script, 364 forms, 297 collection, 275–277 custom elements, 297 elements buttons, read more..

  • Page - 502

    477 ■INDEX Find it faste r at http://superind ex.apr ess.com HEAD element, 85 <head> tag, 85 height attribute, 186 height property, 185 hidden fields, 278–279, 364–365 hide( ) method, 422, 425 HIJAX, 323 history object, 246 home( ) method, 230 host property, 245 hostname property, 245 hover method, 165 :hover pseudo-class, 148–152 href attribute, 110, 137, 235, 246, 249–250, read more..

  • Page - 503

    478 ■INDEX IrfanView, 388 isCallInProgress( ) method, 445 isNaN( ) method, 49, 352 isNumber( ) method, 352 item( ) method, 100 ■J JavaScript object property syntax, 126 JavaScript overview, 1–4 definition, 4 functions, 11 objects, 12–13 problems and merits of, 5–6 reasons for using despite reliability problems, 6–7 running JavaScript, 9 simple example, 13–15 in web page and read more..

  • Page - 504

    479 ■INDEX Find it faste r at http://superind ex.apr ess.com match( ) method, 129, 347, 357 Math object, 30, 357 generating random number, 38 overview, 37 rounding numbers, 37–38 META element, 85 methods of forms, 274–275 of String object, 32–34 of window object animation with window intervals and timeouts, 222–230 changing position and dimensions of window, 221 navigation methods read more..

  • Page - 505

    480 ■INDEX object detection, vs. browser dependence, 65–68 object literal, 82 <object> tag, 153 object-oriented programming (OOP), 3 objects Date object overview, 34 using, 35–37 Math object generating random number, 38 overview, 37 rounding numbers, 37–38 String object creating, 31–32 methods of, 32–34 overview, 30 obj.removeChild(oldNode) method, 109 offsetHeight attribute, 147 read more..

  • Page - 506

    481 ■INDEX Find it faste r at http://superind ex.apr ess.com PRE element, 420, 422, 425 preloading images, 186 presentation layer, changing, 123–131. See also Cascading Style Sheets preventDefault( ) method, 161, 164, 168, 404 previousSibling node, 120 previousSibling property, 103 primitive data types, 18 print( ) method, 230 problems with JavaScript, 5–6 progressive enhancement, read more..

  • Page - 507

    482 ■INDEX Scott, Leland, 340 screen object, 13, 15 screen readers, 69 script block, 9 SCRIPT element, 113, 429, 438, 462 <script> tags, 7, 9, 64, 438 script.aculo.us, 340 scrollbars, 216 search( ) method, 347, 357 search property, 245 select( ) method, 276, 279 select boxes, 242, 286–291, 323–331 SELECT element, 276, 297, 323, 366 selected attribute, 273 selected read more..

  • Page - 508

    483 ■INDEX Find it faste r at http://superind ex.apr ess.com style attribute, 123 style attributes, 127 style collection, 125 style switchers, 136 stylesheet attribute, 138 styling dynamic pages, 131–139 submit( ) method, 274 Submit button, 91, 110, 113, 178, 284, 370 submit handler, 243, 379 substr( ) method, 350 substring( ) method, 32, 42, 347–348, 350 subtraction operator, 27 read more..

  • Page - 509

    484 ■INDEX ■U UAs (user agents), 5, 62, 212 \uDDDD escape sequence, 20 UFO (Unobtrusive Flash Object), 153 UL element, 99, 101, 200, 257, 259–261, 320 uncommenting, 462 Undefined data type, 18 undefined variables, 452–454 Unobtrusive Flash Object (UFO), 153 unobtrusive JavaScript, 62, 153 Upcoming.org, 418 url parameter, 305 useCapture Boolean value, 156 user agents (UAs), 5, 62, read more..

  • Page - 510

    485 ■INDEX Find it faste r at http://superind ex.apr ess.com Willison, Simon, 155 window methods, 239 window object, 25, 90, 97, 165, 213, 215, 238, 245, 413 window parameters, 218 window property, 245 window.back( ) method, 245 window.history object, 246 window.history property, 245 window.location object, 244–245 window.location.href property, 244–245 window.open( ) method, 217, 219 read more..

  • Page - 511

    FIND IT FAST with the Apress SuperIndex ™ Quickly Find Out What the Experts Know L eading by innovation, Apress now offers you its SuperIndex™, a turbocharged companion to the fine index in this book. The Apress SuperIndex™ is a keyword and phrase-enabled search tool that lets you search through the entire Apress library. Powered by dtSearch™, it delivers results instantly. read more..

  • Page - 512

    forums.apress.com FOR PROFESSIONALS BY PROFESSIONALS™ JOIN THE APRESS FORUMS AND BE PART OF OUR COMMUNITY. You’ll find discussions that cover topics of interest to IT professionals, programmers, and enthusiasts just like you. If you post a query to one of our forums, you can expect that some of the best minds in the business—especially Apress authors, who all write with The read more..

Write Your Review