HTML5 Programming with JavaScript For Dummies

RP. 20,000

3 months ago
Full text


  Part I: Understanding the Basics of JavaScript This part of the book helps you gain a perspective of what the language can do for you as a developer and then shows you some simple examples of how the language works. If you’re really in a rush to get to the best material in the book, you can always try to start with Chapter 17 and then go back to earlier chap-ters as necessary when you have questions.

Chapter 1 HTML, Say Hello to JavaScript In This Chapter

  The use of HTML5 andJavaScript together makes it possible for anyone or any organization to move applications from the desktop to the cloud (a special location on theInternet used to store applications and data), where any device capable of running JavaScript can access and use them. (You may want to print the results so that you have a reference to them as you progressthrough the book.) For the purpose of making things easier for everyone, the scripts in this book were tested with the latest version of Firefox available atthe time of writing on a Windows 7 system.

Chapter 1: HTML, Say Hello to JavaScript Discovering the history of JavaScript You won’t find a complete history of JavaScript

  Forexample, whereas Java is a compiled language (one that’s turned into a native executable using a special application) that requires a plug-in to run in yourbrowser, JavaScript is an interpreted language (a text description of what to do that requires an interpreter, another sort of special application, to exe-cute) that requires no special plug-in because the browser provides native support for it. This is why you need to know which platforms support the com- bination of HTML and JavaScript you want to use in your Web pages and whyyou need to test your browser at to ensure the examples in this book will work for you.

Chapter 1: HTML, Say Hello to JavaScript Using JavaScript with any device Some developers are used to the idea that their applications will work only

  Don’t be surprised when the Android user sitting next to you in the doctor’s office is using the application you wrote in JavaScriptfor the PC. Yes, you can get the gist of what’s happening by using a single browser,but it will amaze you to see the application perform the same way no matter which browser you use.

Chapter 1: HTML, Say Hello to JavaScript

  Given the utility of the alert() function, it’s a good addition to your Part I: Understanding the Basics of JavaScript Creating the JavaScript examples This book contains a lot of JavaScript exam- you should use for your example. You can type them if you want using any the file to a location you can easily find on your text editor or an editor designed specifically hard drive and then open it using your browser.for working with JavaScript such as Komodo Opening the file in your browser will cause the JavaScript to run automatically so that you canEdit ( see how your code works. Chapter 2 provideskomodo-edit).

Chapter 1: HTML, Say Hello to JavaScript Placing the code in the page heading Creating a script that runs immediately when you display the page probably

  Add thiscode under the <title> tag in the page you created earlier: <script language=”JavaScript”> function SayHello(){ alert(“This is the SayHello() function!”);}</script> As in the preceding section, you place the script within a <script> tag and tell the browser what language you’re using to create the script. To make this happen, add the following linesof code after the <p> tag in <body> section of the page: <input type=”button” value=”Click Me”onclick=”SayHello()” /> This form of the <input> tag creates a button (specified by the type attri- bute).

Chapter 1: HTML, Say Hello to JavaScript Begin this part of the example by creating a new file using any means you like

  Tosee how this works, add a new button directly after the first button you cre- ated in the preceding section using the following code: <input type=”button” value=”Test External”onclick=”ExternalSayHello()” /> This button works and acts precisely the same as the other button you cre- ated. Figure 1-5: The page Part I: Understanding the Basics of JavaScript Unless you provide additional formatting, the browser simply places the but- tons side by side on the page as shown.

Chapter 2 Assessing Tools of the Trade In This Chapter

  (There are some small differences between the two browsers when you use some of the more esoteric features.)To access the developer tools in Chrome, you click the Customize andControl Google Chrome button, which appears in the upper-right corner of the display and looks like three dashes stacked one on top of the other. For example, if the page requires access to an external JavaScriptfile, the graph shows the time required to perform a Domain Name System(DNS) lookup, connect to the external server, send the request, wait for the server to process the request, and then receive the file.

Chapter 2: Assessing Tools of the Trade Checking out native browsers: Internet Explorer or Safari Depending on the requirements for your application, you may find yourself

  When writing your code initially, you want a browser with strong development features and goodsupport for both HTML5 and JavaScript, but the reality is that you’ll need to write the application in such a way that it does support the native browsers,even when those browsers don’t provide the level of support you’d like. The next section of this chapter, “Checking browser and version,” discusses techniquesyou can use to verify that the user has a usable version of a browser for your Part I: Understanding the Basics of JavaScript Don’t get the idea that native browsers are completely useless or that you can’t perform development work with them.

Chapter 2: Assessing Tools of the Trade Hosting Your Site It’s quite possible to test your application by simply loading the page into a

  Providing more than a brief overview of this option is outside the scope of this book, but you do need to be aware that the option exists. For example, it pays to check on issues such as potential bandwidth throttling(the act of limiting the amount of data that the hosted site can accept, even Part I: Understanding the Basics of JavaScript Using JavaScript from your computer You can host JavaScript applications from your computer when you have a server such as Apache or Internet Information Server (IIS) installed.

10. Click Finish

  Installing Apache on Mac OS X The amazing thing is that you don’t have to install Apache on your Mac — the server is already installed. Type the following code into the editor, replacing USERNAME with your username: <Directory “/Users/kdarosett/Sites/”>Options Indexes MultiviewsAllowOverride AuthConfig LimitOrder allow,denyAllow from all</Directory> 4.

Chapter 2: Assessing Tools of the Trade • To restart Apache: Type sudo apachectl restart

  If this is the case on your system, you should be able to open a browser, type localhost in the address bar,press Enter, and see a message. InstallingApache is one of the installation options that you receive when working with most versions of Linux and this is the easiest way to install Apache.

5. Start the server:

  You see the name and version number of your browser, butthis time through the Web server instead of as a loaded file. This file always contains the location of the various folders that Apache uses, so if you find that you can’t locate a particularfolder for your setup, refer to the httpd.

Chapter 3 Integrating HTML5 and JavaScript In This Chapter

  ▶ Performing simple output tasks ▶ Understanding the format of JavaScript statements▶ Creating JavaScript comments to document your code ▶ Alerting users to the need to turn on JavaScript support he previous two chapters introduce you to JavaScript and the tools needed to work with it, but they don’t really discuss JavaScript as a lan- T guage. In this case, you must access the attribute within thecontrol and make the change there, as shown here: document.getElementById(“btnClickMe”).setAttribute( Part I: Understanding the Basics of JavaScript In this case, you ask JavaScript to obtain access to the btnClickMe <input> element in the document and then to set the value attribute to Clicked!.

Chapter 3: Integrating HTML5 and JavaScript The

  For example, when you type document.body.bgColor, you tell JavaScript that you want to change the background color of the body element of the current document. (You can find the full code for this example in the \Chapter 03\Statements folder of Part I: Understanding the Basics of JavaScript <script language=”JavaScript”> function WriteText(){ document.getElementById(“First”).innerHTML =“Changed First”; alert(“Check First!”); document.getElementById(“Second”).innerHTML =“Changed Second”;}</script> The first statement changes a <p> element with an id of First.

Chapter 3: Integrating HTML5 and JavaScript Defining basic code blocks You’ve probably noticed that the coding examples use curly brackets to

  When you want to set a property to a new value, the description of which property to change can appear on one line and the new value on the second line. (You can find the full code for this exam-ple in the \Chapter 03\Comments folder of the downloadable code asMultipleStatements.HTML.) function WriteText() {// Change the first statement, then wait so the // user can see the change.document.getElementById(“First”).innerHTML =“Changed First”; alert(“Check First!”); // Wait here.

Chapter 3: Integrating HTML5 and JavaScript Each line begins with a double slash (//) to indicate that it’s a comment line. Notice that you can begin a comment after the code in a line, as shown in the

  Commenting out code is a common technique where a developer addstwo forward slashes (//) in front of a line of code that the developer sus- pects is causing problems in the application. ✓ Understand JavaScript objects and discover how to use them.✓ Create and use Boolean, number, text, and array objects.✓ Develop custom objects to use in your applications.✓ Pass data using object literals.✓ Discover the details of using the Object, Number, String, Date, and RegExp objects.

Chapter 4 Embracing JavaScript Variables In This Chapter

  You store the data until you need to use it in the application, take the data out, do something with it, and then put it back intothe variable when you’re done. However, you also need to remember that variables are simplyphysical memory locations to the computer that just happen to have a par- ticular sequence of electrical impulses in them.

Chapter 4: Embracing JavaScript Variables Declaring variables To use a variable, you must tell JavaScript to create it. After all, when you want to store something in a box in real life, you must first acquire the box. There’s no JavaScript store where you go to buy a box — you simply tell JavaScript you need one by using the var keyword, followed by the variable

  To place something in the box immediately, you use the assignment operator (=), which assigns the value to the box, and you must also providewhat you want to store in the variable. (You can find the full source code for this example in the \Chapter 04\SimpleVariables folder of the downloadable code as TestNullAndUndefined.HTML.) function UseVariable() { // Create an undefined variable and test it.var MyVariable; alert(MyVariable + “ has a type of: “ +typeof(MyVariable)); // Define the variable and test again.

Chapter 4: Embracing JavaScript Variables // Empty the variable of data and test again. MyVariable = null;

  When the code uses the alert() function to display the content of MyVariable, you see the word, undefined, in the resulting dialogbox. For now, all you need to really understand is that Boolean variables are tra- ditionally used to make a decision or to tell the user the truth value of theBoolean variable (possibly as the result of performing a calculation or check- ing the status of data).

Chapter 4: Embracing JavaScript Variables Most JavaScript applications perform some sort of math tasks (amongst

  Part II: Speaking the JavaScript Language Table 4-1 (continued) Operator Example Description The division operator divides the / MyNumber = 11 / 5; leftmost value by the rightmostvalue in the expression to the right of the assignment operator andplaces the result in MyNumber. Inaddition, this comparison verifies that the type of the value on the left is the same as the type of the valueon the right.

Chapter 4: Embracing JavaScript Variables Using the logical operators Logical operators help you perform Boolean logic. You use them to perform

  In this case, the expression evaluates to truebecause both sub-expressions are true.|| ((5 < 10) || (10 < 5))The OR operator combines two expressions such that one sub-expression or the other canbe true and make the entire expression true. Part II: Speaking the JavaScript Language Table 4-5 AND Operator Logic Expression 1 Expression 2 Result true true true false true falsetrue false false false false false Table 4-6 OR Operator Logic Expression 1 Expression 2 Result true true true false true truetrue false true false false false Using the grouping operators JavaScript supports the use of parentheses as grouping operators.

Chapter 4: Embracing JavaScript Variables Value1:

  This figure also shows the result of performing a division using the two input numbers. Each button has a different JavaScript function associated with it.

3. Change the value attribute of Result to reflect the math operation on Value1 and Value2

  Here’sthe code used to perform addition: function DoAdd() { // Obtain the current values of Value1 and Value2.var Value1 = new Number( document.getElementById(“Value1”).value);var Value2 = new Number( document.getElementById(“Value2”).value);// Set the result to reflect the addition // of the two numbers.document.getElementById(“Result”).setAttribute(“value”, Value1 + Value2);} The code begins by creating a number using the new keyword. You place the global variable, ThisNumber, in the <head> section of the page like this: <script language=”JavaScript”> var ThisNumber = 22.5</script> A global variable is one that you can access anywhere on the current page.

Chapter 4: Embracing JavaScript Variables Working with Text The string data type (text) is the presentation format that most humans think

  Keeping this flexible nature in mind, here are four formatting func- tions to start off your library of JavaScript string functions: ✓ toLocaleLowerCase(): Changes all the characters in a string to lower- Part II: Speaking the JavaScript Language ✓ toLocaleUpperCase(): Changes all the characters in a string touppercase versions while respecting the uppercase rules for the current locale. (You can find the complete source code forthis example in the \Chapter 04\Arrays folder of the downloadable code as CreateArray.HTML.) Part II: Speaking the JavaScript Language <body><h1>Creating Arrays</h1><h2>Regular:</h2><script language=”JavaScript”> // Create the array.var Colors = new Array(); // Fill the array with data.

Chapter 5 Working with Objects In This Chapter

  JavaScript doesn’t care what you call the objects and variables you create as long as the namedoesn’t violate any of the naming requirements that JavaScript must use to recognize the word as an object or variable. Of course, the apple isn’t real — it’sa model of a real-world apple, but the idea is that you can envision what this apple would look like based on the description you provide for it.

Chapter 5: Working with Objects Any special instructions required to create an object based on the class

  Exploring JavaScript browser objects Here’s a quick overview of some of the more interesting JavaScript browser objects — those that relate to how the browser performs tasks: Part II: Speaking the JavaScript Language ✓ location: Contains information about the current URL. You can see a complete list of the methods and properties associated with this object at✓ Node: Defines the particulars of any given node, which can include the document as a whole, an element within the document, an attributeprovided as part of an element, text, and comments.

Chapter 5: Working with Objects // Display the <p> tag on the page

  To display the<p> tag, the code calls document.body.appendChild() to add the <p> tag to the rest of the information on the page. After defin-ing the class elements, the example creates an instance of the class, pro- vides data for each of its properties, and then uses a method to output theclass data as a formatted string.

Chapter 5: Working with Objects // Create the customer class

  Theimportant elements are to enclose the data within curly brackets, to provide a name for each value, to separate the value from the name by a colon, and toseparate values with commas. The easiest method of accomplishing this task is to simply type the name of a new property and assign a value to it.

Chapter 6 Getting to Know the Standard JavaScript Objects In This Chapter

  Defining the Basic JavaScript Objects It’s time to look at some of the tasks you can perform with individual objects — including the creation of more complex custom objects based on the Objectclass. (The customobjects you see in later chapters build on this one.)One of the problems with the example in Chapter 5 is that it shows how to create a method as a property.

Chapter 6: Getting to Know the Standard JavaScript Objects The following code shows how to create a more advanced custom class

  You can also pro-vide an optional starting position within the source string to begin the search.✓ match(): Searches for matches between a regular expression (seethe “Working with regular expressions” section, later in this chapter, for details) within a source string and returns the matches as numericvalues.✓ replace(): Replaces a match between a regular expression or searchstring with the specified replacement value in a source string. For example, if you replaced the letter e in Rested with the letter u, you’d see an output of Rusted.✓ search(): Searches for matches between a regular expression within asearch string and returns the first match as a numeric value.✓ slice(): Removes the specified portion of a source string and returnsthat part as a new string.

Chapter 6: Getting to Know the Standard JavaScript Objects JavaScript used to include a getYear() method. This method is depre-

  Part II: Speaking the JavaScript Language ✓ \0: Represents the null (NUL) character often used to terminate strings.✓ \n: Represents the newline character.✓ \f: Represents the form feed character.✓ \r: Represents the carriage return character.✓ \t: Represents the tab character.✓ \v: Represents the vertical tab character.✓ \xxx: Find the character specified by the octal number xxx. ✓ n $: Searches for n at the end of the string.✓ ^n: Searches for n at the beginning of the string.✓ ?=n: Finds a string that’s followed by a specific string n.✓ ?!n: Finds a string that isn’t followed by a specific string n.

Chapter 6: Getting to Know the Standard JavaScript Objects Using the RegExp search modifiers Search modifiers define how RegExp performs a search. For example, you

  can tell RegExp that you want to search for all instances of a search expres- sion, rather than just one instance. The following list describes the searchmodifiers: ✓ i: Specifies that you want to perform a case-insensitive search whereAbc is treated the same as aBc.

g: Performs a global search where the search returns all possible matches, rather than returning just the first match

  The following list describes the properties you get withRegExp: ✓ global: Returns true when the object has the g modifier set.✓ ignoreCase: Returns true when the object has the i modifier set.✓ lastIndex: Specifies the index at which to start the next search. Remember that the index is zero-based, so if you want to start searching at the second character, you provide a value of 1.✓ multiline: Returns true when the object has the m modifier set.✓ source: Contains the search expression used by RegExp.

Chapter 6: Getting to Know the Standard JavaScript Objects Calculating differences in dates Determining the time span between events is an important part of many

  The application uses the Date objectone way or the other, but that’s the application’s view of the object, rather than a determination the object has made. ✓ Discover how to use functions to create neater applications that have fewer errors and are easier to maintain.✓ Create applications that can make decisions of various sorts, which improves overall application flexibility.✓ See how to repeat a set of steps as needed to complete a task a specific number of times.✓ Understand how errors creep into applications, how to discover them, and what to do to fix them.

Chapter 7 Using Functions In This Chapter

  ✓ asin(x): Calculates the arcsine of x in radians.✓ atan(x): Calculates the arctangent of x as a numeric value between ✓ ceil(x): Rounds the value of x up to the nearest integer value.✓ cos(x): Calculates the cosine of x, where the value of x is in radians. (You can find complete code for the examples in the following sections in the \Chapter 07\Functions folder of the download-able code as UsingFunctions.HTML.)When working through these functions, you may find that you encounter some browser idiosyncrasies.

Chapter 7: Using Functions Unfortunately, some developers go overboard and use too many functions

  ✓ Consider creating a new function when the code you’ve written takes up more than a single page — a function is easier to understand when youcan see all of the code on a single screen. In this case, the caller adds some additional text to the output and dis- plays it onscreen, as shown here:function DisplayReturn(){ // Output the param onscreen.document.getElementById(“Result”).innerHTML =“The return value is: “ + TestReturn();} Using return values lets you nest function calls as deeply as needed to per- form complex tasks.

Dokumen baru

Aktifitas terbaru

Download (411 Halaman)
RP. 20,000