[go: up one dir, main page]

0% found this document useful (0 votes)
428 views616 pages

Untitled

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
428 views616 pages

Untitled

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 616
TRAINING & REFERENCE murach's |. JavaScript and jQuery Zak Ruvalcaba Mike Murach Mike Muracu & AssociAtes, INc. 4340 N. Knoll Ave. + Fresno, CA 93722 wwwmurach.com * murachbooks@murach.com Editorial team Authors: Zak Ruvaleaba Mike Murach Editors: Anne Boehm Ben Murach Cover design: Zylka Design Productior Maria Pedroza David-Spera Books for web developers Murach's HTMLS and CSS3 Murach's JavaScript and jQuery Murach's JavaScript and DOM Scripting Murach’s PHP and MySQL Murach’s Java Servlets and JSP (Second Edition) Murach’s ASP.NET Web Programming with C# Murach's ASP.NET Web Programming with VB Books on core Java, C#, and Visual Basic Murach’s Java Programming Murach's C# Murach’s Visual Basic Books for database programmers Murach’s MySQL Murach's Oracle SQL and PL/SQL Murach's SQL Server 2012 for Developers Murach’s ADO.NET Database Programming with C# Murach’s ADO.NET Database Programming with VB For more on Murach books, please visit us at www.murach.com © 2012, Mike Mura llrightsreserved. ch & Associates, Ine. Printed in the United States of America 10987654321 ISBN: 978-1-890774-10-7, Contents Introduction Section 1 Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Section 2 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Section 3 Chapter 12 Chapter 13 Section 4 Chapter 14 Chapter 15 Chapter 16 Section 5 Chapter 17 Chapter 18 Reference Appendix A. Appendix B Appendix C Index JavaScript essentials Introduction to web development Getting started with JavaScript How to work with objects, functions, and events How to test and debug a JavaScript application How to work with arrays How to script the DOM with JavaScript jQuery essentials Getting off to a fast start with jQuery How to use effects and animations How to use the DOM manipulation and traversal methods How to work with forms and data validation How to create and use plugins jQuery UI essentials Get off to a fast start with jQuery Ul themes and widgets How to use jQuery UI interactions and effects Ajax, JSON, and API essentials How to use Ajax, JSON, and Blogger How to use the APIs for YouTube, Twitter, and Flickr How to use the API for Google Maps jQuery Mobile essentials Get off to a fast start with jQuery Mobile How to enhance a jQuery Mobile web site Aids How to set up your computer for this book A summary of the applications in this book How to resolve $ conflicts iii 49 ol 9 14 157 343 379 405 439 469 497 S71 581 585 588 Expanded contents Expanded contents Section 1 JavaScript essentials Chapter 1 Chapter 2 Indroduction to web development How a web application works. The components of web application. How static web pages are processed. How dynamic web pages ae processed. How JavaScript and jQuery ae use for client-side processing. The components of a JavaScript application. How the Email List application works. ‘The HTML. The CSS.. ‘The JavaScript The HTML and CSS skills that you need for this book, How to use the HTMLS semantic clements. How to use the div and span elements. How to use the basic HTML attributes. How to provide CSS styles for an HTML page. How to code the basic CSS selectors. How to code CSS ruleset. How to test a JavaScript application How to run a JavaScript application, How to ensure cross-browser compatiblity How to use Aptana to develop JavaScript applications. How to create a project. How to open or close an HTML, CSS, or JavaScript fle. How to change the colors that highlight the syntax. How to edit a file. How to run a JavaScript application, Getting started with JavaScript How to include JavaScript in an HTML document ‘Two ways to include JavaScript in the head of an HTML document How to include JavaScript in the body of an HTML document The JavaScript syntax. How to cove JavaScript statements. How to create identifiers. How to use comments, How to use objects, methods, and properties. How to work with JavaScript data. ‘The primitive datatypes. How to code numeric expression. How to work with numeric variables. How to work with string and Boolean variables How to use the parselot and parseFloat method: How to code control statements. How to code conditional expressions. v vi Expanded contents Chapter 3 Chapter 4 Chapter 5 How to code if statements. svesuananeneanine 74 How to code while and do- How to code for loops Two illustrative applications. The Miles Per Gallon application The Test Scores application. How to find errors in your code. How to gt error messages with Firefox. Common JavaScript eto. How to work with objects, functions, and events How to use objects to work with data. How to use the window and document objects, How to use Textbox and Number object How to use Date and String object How to use DOM objects to change the text for an element. How to use function How to ereate and call an anonymous function . How to create and call a named function. When and how to use local and global variables. How to handle events. How to attach an event handler to an event How to use an onload event handler to attach the other event handler Two illustrative applications. The Mile Per Gallon application, ‘The Email List application .. How to test and debug a JavaScript appli An introduction to testing and debuggin “Typical test phases fora JavaScript application ‘he three types of errors that ean occu Common JavaScript ero. How top-down coding and testing can simplify debugging. How to debug with Firebug. How to enable Firebug and find errors.. How to use breakpoints and ste through code. Other debugging methods. When and how to got ervor messages with ther browsers. A simple way to trace the execution of your JavaScript cod When and how to view the source code When and how to validate the HTM How to work with arrays How to create and use an array.. How to reate an array and refer to its elements How to add and delete array clement. How to use for loops to work with ara How to use for-in loops to work with arrays. How to use the methods of an Array ob An enhanced Email List application. ‘The user interface and HTML.. ‘The JavaSeri Chapter 6 Section 2 Chapter 7 Expanded contents How to script the DOM with JavaScript DOM scripting properties and methods. DOM seriping concept, ‘The Node interface .. ‘The Document and Element interfaces....... The FAQs application. The usr interface, HTML, and CSS. ‘The JavaScript Anotber way t Two critical i Usability Accessibilit ‘The FAQs apy DOM scripting skills for links and images. How to cancel the default action of an event How to preload images, The Image Swap applicatior ‘The HTML and CSS. so ‘The JavaScript. PP ssues for JavaScript applications. The Slide Show application ‘The HTML and CSS. ‘The JavaScript jQuery essentials Get off to a fast start with jQuery Introduction to jQuer What jQuery i How to include jQuery a How jQuery cai simplify JavaScript development. How jQuery can affect testing and debugging. How jQuery UL and plugins can simplify JavaScript development. The basics of jQuery programming.. How to code jQuery selecto: How to call jQuery methods How to use jQuery event methods, The Email List application in jQuery. ‘The user interface and HTML.. The jQuer ‘A working subset of selectors, methods, and event methods ‘The most useful selectors, The most useful methods. The most useful event methods. Otter event methods that you should be aware Three illustrative applications. ‘The FAQs application in jQuery. vii viii Expanded contents Chapter 8 Chapter 9 Chapter 10 ‘The Image Swap application in jQuery ‘The Image Rollover application in jQuery How to use effects and animations How to use effects The jQuery methods for effects. ‘The FAQs application with jQuery effects.. Slide Show application with effects. ‘The usr interface, HTML, and CSS “Two ways to code the jQuery How to stop and start aside sho How to use animation. How to use the basic syntax of the animate method. How to chain animate methods How to use the delay and stop methouls How to use casings with effets and animations, How to use the advanced animate syntax and the methods for working with queues. A Carousel application with animation .. The usr interface, HTML, and CSS, ‘The jQuery.. How to use the DOM manipulation and traversal methods The DOM manipulation methods... .260 The methods for working wth attributes. ‘The methods for DOM replacement, ‘The methods for DOM insertion and clonin ‘The methods for DOM wrapping and removal. The TOC application. ‘The user interface and HTMI ‘The jQuery The methods for working with styles and positionin The methods for working with styles. The methods fr positioning elements, ‘The enhanced TOC application. The DOM traversal methods. The tre traversal methods. ‘The filtering methods. A Slide Show application that uses DOM traversal method How to work with forms and data val Introduction to forms and controls.. How forms wor ‘The HTMLS and How to use jQuery to work with form ‘The jQuery selectors and methods fr forms. The jQuery event methods for forms. A Validation application that uses JavaScript. ‘The user interface and HTML. Some of the JavaScript for the application. Chapter 11 Section 3 Chapter 12 Expanded contents How to use a plugin for data validation, How to us the validation plugin. ‘The options and default tor messages forthe validation plugin A Validation application that uses the validation plugin ‘The usr interface. ‘The HTML. The CSS. How to create and use plugins Introduction to plugins. How to find jQuery plugins. Some of the most useful plugin. How to use any plugin, How to use four of the most useful plugins, How to use the Lightbox plugin for image How to use the bxSlider plugin fr carousels, How to use the Cyele plugin for slide shows. How to use the jLayout plugin for rwo-column layouts. How to create your own plugins. ‘The structure of a plugin How to code a plogi that highlights menu items. How to ad options toa plugin, ‘A web page that uses two plugins. ‘The user interfac ‘The scrip elements ‘The HTML for the elements use ‘The jQuery for using the plugins. jQuery Ul essentials Get off to a fast start with jQuery UI themes and widgets Introduction to jQuery U What jQuery Ul is and where to get it ‘The jQuery Ul components, How to build and use a jQuery Ul download. How to build a download. How to use ThemeRolle to build a custom theme. How to use the downloaded folders and file. How to use jQuery UI widgets.. How to useany widget. How to use the Accordion widget. How to use the Tabs widget. How to use the Button and Dialog widgets. How to use the Autocomplete widget. How to use the Datepicker widget. How to use the Slider widget, How to use the Progeessbar widget ‘A web page that uses jQuery Ul. The usr interface ‘The link and script element ssonsnnonnn ddd x Expanded contents Chapter 13 Section 4 Chapter 14 Chapter 15 How to use jQuery UI interactions and effects How to use interactions Intcoduction to imeractions. . How to use the draggable and droppable interactions. How to use the resizable interaction. How to use the selectable interaction How to use the sortable interaction How to use effects. Introduction to effects. How to use individual effects. How to use color transitions. How to use class transitions. How to use visibility transitions, Ajax, JSON, and API essentials How to use Ajax, JSON, and Blogger Introduction to Ajax. How Ajax work Common data formats for Ajax. ‘The members of the XMLHttpRequest object. How to use the XMLHttpRequest object. How to use the jQuery shorthand methods for Ajax.. ‘The jQuery shorthand methods for working with Ajax, How to use the load method to load HTML dat: How to use the $.get or §.post method to load XML data.. Howto use the .getSON method to load JSON data... How to send data with an Ajax request. How to use the $.ajax method for working with Ajax. ‘The syntax ofthe Sajax method How to use the $.ajax method to load data. How to use Ajax with the API for Google's Blogger. Inteoluction o Google's Blogg How to use the API fr Blogger, How to use an online ISON editor to review the feed fom a web st How to use Ajax and JSON to display Blogger posts, How to use the APIs for Youtube, Twitter, and Fli How to use Ajax with YouTube How to use the API for YouTubs ‘The query parameters and data items that you'll use the most, How to list videos by channel How to list videos by search term. How to play videos in a video player on your site. How to use Ajax with Twitter. How to use the API for Twitter. How to display the tweets for a user, How to convert the URLs within tweets to links, How to display a timestamp for each tweet. Chapter 16 Section 5 Chapter 17 Expanded contents How to use Ajax with Flickr.. How to use the API for Flick, ‘The query parameters and data items that you'll use the most, How to display titles and descriptions for a Flickr photo feed. How to display a gallery of Flickr photos. How to use the API for Google Maps Introduction to Google Maps. Introduction to the Google Maps API.. ‘The classes for adding & Google map to 8 web pas “The scrip element forthe Google Maps APL How to add a Google map to a web page. How to display markers on a map. ‘The classes and methods for geocoding and markers, How to ereate an address list that displays markers. How to display messages on a map. The lasses and methods for messages and markers. How to add messages to markers, How to add custom messages to markers How to add Flicks images to message. How to display driving directions. The classes and methods for directions and listener. How to display driving directions on your own ste, jQuery Mobile essent Get off to a fast start with jQuery Mobile How to work with mobile device: How to provide pages for mobile devices. How to use a JavaScript plugin to rediret mobile browsers to a mobile web sit, How to set the viewport properties. Guidelines for designing mobile web page Guidelines for testing mobile web pages, How to get started with jQuery Mobile What jQuery Mobile i and where to get it How to inclide jQuery Mobile in your web pages How to create one web page with jQuery Mobile How to code multiple web pages n'a single HTML file. How to use dialogs and transitions. How to ereate buttons. How to create a navigation bar.. How to style web pages with jQuery Mobile. How to work with the default styles. How to apply theme swatches to HTML elements. How to use ThemeRoller to roll your own theme. A mobile web site for Vecta Cory The layout ofthe web st ‘The HTML for the mobile web site. ‘The style sheet for the mobile web sit xi xii Expanded contents Chapter 18 How to enhance a jQuery Mobile web site How to use the jQuery Mobile documentatior “The components of jQuery Mobile, ‘The data attributes of jQuery Mobile.. The events and methods of jQuery Mobil. How to use jQuery Mobile for content formatting, How to lay out contet in grids. How to use collapsible content blocks How to use collapsible ses How to use jQuery Mobile for list views. How to use base lists How to use spit button lists and inet lis How to use list dividers and count bubbles How to use search filter bars. How to use jQuery Mobile for forms. How to use text fields and text areas. How to use sliders and switches. How to use radio buttons and check boxes How to use select menu: How to submit form. ‘An enhanced mobile web site for Vecta Corp. ‘The layout of the web site. ‘The HTML. The style shec Introduction {Query isa free, open-source, JavaScript library that provides dozens of methods that make JavaScript programming easier. Beyond that, the jQuery methods are coded and tested for cross-browser compatibility, so they will work in all browsers. Those are just two of the reasons why jQuery is used by more than half of the 10,000 most-visited web sites today. In fact, you can think of jQuery as one of the four technologies that every web developer should master: HTML, CSS, JavaScript, and jQuery. But don't forget that jQuery is actually JavaScript, and to use jQuery you need to know some JavaScript. That’s one of the reasons why jQuery has been so hard to learn. That’ also why this book starts by teaching you the least you need to know about JavaScript for effective use of jQuery, This is essential for programming novices, but it’s also useful for readers with some JavaScript experience, Then, this book uses a highly-structured approach to present all of the jQuery, jQuery UL (User Interface), and jQuery Mobile skills that you will need on the job, and it always presents these skills in the context of useful, real-world applications. book does ike sure you have all of the JavaScript skills that you need for using {iQuery, the six chapters in section I of this book present a crash course in those skills. If you already know JavaScript, you can skim this section, but you'll probably pick up a few new skills as you do that. If you're a programming novice, this section is especially designed to get you off toa good start. © Once you have the JavaScript skills that you need, the five chapters of section 2 present the core jQuery skills that every web developer should have, Chapter 7 gets you off to a fast start with those skills, and the next four chapters focus on effects and animations, DOM scripting, working with forms and data validation, using the many plugins that are available for jQuery, and creating your own plugins. xiv Introduction + Besides the core jQuery library, jQuery provides the jQuery Ul (User Interface) library. This library helps you build advanced features with just a few lines of code, and the two chapters in section 3 show you how to rake the best use of jQuery UL. That includes the use of widgets like tabs, accordions, and datepickers..interactions like draggable, droppable, and sortable...and effects like color and class transitions. ‘© The three chapters in section 4 show you how to use Ajax and JSON to get data from a server and add it toa web page without reloading the entire web page. They also show you how to use the APIs for web sites like Blogger, YouTube, Twitter, Flickr, and Google Maps because that’s a common use of Ajax and ISON. ‘© Last, the two chapters of section 5 show you how to use jQuery Mobile to develop web applications for mobile devices like iPhones and Android phones. As we see it, this is the best way to develop mobile web sites right now, so this too is something every web developer should know. Why you'll learn faster and better with this book Like all our books, this one has features that you won't find in competing books. That’s why we believe you'll learn faster and better with our book than with any other, Here are a few of those features. © Because section | presents a complete subset of the JavaScript that you need for using jQuery, you will be able to understand all of the JavaScript that’s used in the jQuery applications in this book. In contrast, most jQuery books don't teach JavaScript, so you often need to refer to other sources when you don’t understand the JavaScript that they use in their examples. © Ifyou page through this book, you'll see that all of the information is presented in “paired pages,” with the essential syntax, guidelines, and examples on the right page and the perspective and extra explanation on the left page. This helps you learn faster by reading less..and this i the ideal reference format when you need to refresh your memory about how to do something. ‘© To show you how jQuery works, this book presents dozens of complete ‘Query applications that range from the simple to the complex. To see how that works, take a quick look at the four applications that are presented in the first jQuery chapter: figures 7-7 and 7-8, figure 7-12, figures 7-13 and 7-14, and figure 7-15. This also shows how our paired pages make it easy to study the relationships between the HTML, CSS, and JavaScript code. Then, look at the summary of all of the book applications in appendix B. © Of course, this book also presents dozens of short examples, so it’s easy to find an example that shows you how to do what you want to do, Even better, cour paired pages make it much easier to find the example that you're looking for than itis with traditional books in which the examples are embedded in the text. Incidentally, all of the examples in this book use HTMLS and Introduction XW CSS3 so they illustrate the best web development practices of today. ‘© As you proceed through this book, you will learn how to use almost all of the selectors, methods, and event methods that jQuery provides. That means that you can use this book as a reference that will help you parse the code in any jQuery application, So, although no one book can present every type of jQuery application, this book prepares you to understand any application that you encounter on the job, on web sites, or in other books. What software you need To develop JavaScript and jQuery applications, you can use any text editor, However, a text editor that includes syntax coloring and auto-completion will help you develop applications more quickly and with fewer errors, That’s why we recommend Aptana Studio 3 for both Windows and Mac OS users, Although Aptana is free, it provides many powerful features, Then, to test a web page, Windows users can use Internet Explorer and Mac users can use Safari, because those are their default browsers. But we also recommend that you test your pages in a second browser like Mozilla Firefox, which is also free. In practice, you should also test your pages in Opera and Chrome, but that isn't necessary as you learn, If you decide to use Aptana, chapter | presents a short tutorial that will get you started right. And to help you install Aptana and Firefox, appendix A provides the web site addresses and procedures that you'll need. How our downloadable files can help you learn If you go to our web site at www.murach.com, you can download all the files that you need for getting the most from this book. These files include: © the files for all of the applications in this book © the files that you will use as the starting points for the exercises ‘© the files that provide the solutions to the exercises These files let you test, review, and copy the code. In addition, if you have any problems with the exercises, the solutions are there to help you over the learning blocks, which is an essential part of the learning process. And sometimes, the solutions will show you a more elegant way to handle a problem, even when you've come up with a solution that works. Here again, appendix A shows you how to download and install these files. Support materials for trainers and instructors If you're a corporate trainer or a college instructor who would like to use this book fora course, we offer an Instructor's CD that includes: (1) a complete set cof PowerPoint slides that you can use to review and reinforce the content of the book; (2) instructional objectives that describe the skills a student should have xvi Introduction upon completion of each chapter; (3) test banks that measure mastery of those skills; (4) extra exercises and projects that prove mastery; and (5) solutions to the extra exercises and projects. To learn more about this Instructor's CD and to find out how to get it, please go to our web site at www.murach.com and click on the Trainers link or the Instructors link. Or, if you prefer, you can call Kelly at 1-800-221-5528 or send an email tokelly@murach.com, Companion books Since jQuery, HTML, and CSS are so tightly linked, we highly recommend that you know HTMLS and CSS3 as well as you know jQuery. To gain that expertise, you'l find that Murach’s HTMLS and CSS3is the perfect companion to this jQuery book. With these two books at your side, you'll be able to develop ‘web pages that use HTMLS, CSS3, and jQuery the way the best professionals do. If you want to learn more about JavaScript so you can do the type of client- side programming that jQuery doesn't provide for, we recommend Murach’s JavaScript and DOM Scripting. It presents all of the JavaScript skills that aren't presented in this jQuery book, including how to use regular expressions, how to create and use your own objects, and much more. It is also a great reference. If you want to learn server-side web programming when you finish this book, we offer several books that will help you. Our ASP.NET books will show ‘you how to develop web applications with C# or Visual Basic. Our Servlets and ISP book will show you how to develop web applications with Java, And our PHP and MySQL book will show you how to develop web applications with PHP as the scripting language and MySQL as the databas To find out more about our new books and latest editions, please go to our web site at wawamurach.com. There, you'll find the details for all of our books, including complete tables of contents. Please let us know how this book works for you From the start of this project, we had three goals, First, we wanted to take a new approach to jQuery that lets you learn faster and better than ever. Second, ‘we wanted this book to work for programming novices as well as it works for experienced JavaScript programmers. Third, we wanted to raise the skills of our readers to a professional level. Now, we hope we've succeeded, We thank you for buying this book. We wish you all the best with your jQuery development, And if you have any comments, we would appreciate hearing from you. Zak Ruvalcaba, Author Anne Boehm, Editor zak@modulemedia.com anne@murach.com JavaScript essentials In the six chapters inthis section, you will learn all of the JavaScript essentials that you need for working with jQuery. To start, chapter | presents the concepts and terms that you need for developing JavaScript applications. It also shows you how to use the Aptana IDE that we recommend for developing JavaScript applications. Next, chapter 2 presents a starting subset of the JavaScript language, chapter 3 completes that subset, and chapter 4 shows you how to test and debug a JavaScript application, At that point, you'll be able to start, developing applications of your own. ‘Then, chapter 5 shows you how to use arrays, which are commonly used in JavaScript applications. Last, chapter 6 shows you how to use all of the JavaScript skills that you've learned thus far to do some DOM scripting with links and images. ‘When you complete these chapters, you'll be able to develop useful JavaScript applications. Beyond that, though, you'll have all of the JavaScript skills that you need for using jQuery, Then, you can master {Query by reading the last four sections of this book. Introduction to web development This chapter presents the background concepts, terms, and skills that you need for developing JavaScript applications. That includes a quick review of the HTML and CSS skills that you need. That also includes a quick tutorial on how to use Aptana Studio 3, which is the IDE that we recommend for developing JavaScript applications. If you have some web development experience, you should be able to go through this chapter quickly by skimming the topics that you already know. But if you're new to web development, you should take the time to master the concepts and terms of this chapter. How a web application works.. ‘The components of a web applications How static web pages are processed How dynamic web pages ae processed How JavaScript and jQuery ae used for client-side processing. The components of a JavaScript application.. How the Email List application Works. The HTM The CSS.. The JavaScript. The HTML and CSS skills that you need for this book. How to use the HTMLS semantic elements. How to use the div and span elements. How to use the basic HTML attributes. How to provide CSS styles for an HTML page How to code the basie CSS selectOrSsssmsn How to code CSS rule sets How to test a JavaScript application.. How to run a JavaScript application suse How to ensure cross-browser compatibility. 32 How to use Aptana to develop JavaScript applications...34 How to create a project sn How to open or close an HTML, CSS, or JavaScript fe, How to change the colors that highlight the syntax. How toedita file. How to run a JavaScript application. Perspective Section 1 JavaSeript essemtials How a web application works A web application consists of many components that work together as they bring the application to your computer or mobile device. Before you can start developing JavaScript or jQuery applications, you should have a basic under standing of how these components work together. The components of a web application The diagram in figure 1-1 shows that web applications consist of clients and a web server. The clients are the computers, tablets, and mobile devices that use the web applications. They access the web pages through programs known as, web browsers. The web server holds the fies that make up a web application. ‘Anebworkis a system that allows clients and servers to communicate, The Internets a large network that consists of many smaller networks. In a diagram like the one in this figure, the “cloud” represents the network or Internet that connects the clients and servers. In general, you don’t need to know how the cloud works, But you should havea general idea of what’s going on, To start, networks can be categorized by size. A local area network (LAN) is.a small network of computers that are near each other and can communicate with each other over short distances, Computers in a LAN are typically in the same building or adjacent buildings. This type of network is often called an intranet, and it can be used to run web applications for use by employees only. In contrast, a wide area nezwork (WAN) consists of multiple LANs that have been connected. To pass information from one client to another, a router determines which network is closest to the destination and sends the information over that network. A WAN can be owned privately by one company or it can be shared by multiple companies. ‘An Internet service provider (ISP) is a company that owns a WAN that is connected to the Internet. An ISP leases access to its network to companies that need to be connected to the Internet. Chapter 1 Introduction to web development The components of a web application Computer ‘Smart Phone Description © A web application consists of clients, a web server, and a network. © The clients use programs known as web browsers to request web pages from the web server. Today, the clients can be computers, smart phones like the iPhone, or tablets like the iPad. © The web server returns the pages that are requested to the browser. Anetwork connects the clients to the web server. © Anintranet isa local area network (or LAN) that connects computers that are near each other, usually within the same building. © The Mnterner is a network that consists of many wide area networks (WANS), and each of those consists of two or more LANS, Today, the Internet is often referred to as “the Cloud”, which implies that you really don't have to understand how it works. © Aninternet service provider (ISP) owns a WAN that is connected to the Internet. Figure +1 The components of a web application Section 1 JavaSeript essemtials How static web pages are processed A.static web page like the one in figure 1-2 is a web page that doesn't change each time itis requested. This type of web page is sent directly from the web server to the web browser when the browser requests it. You can spot static pages in a web browser by looking at the extension in the address bat. Ifthe extension is .htm or html, the page is a static web page. The diagram in this figure shows how a web server processes a request for a static web page. This process begins when a client requests a web page in a ‘web browser, To do that, the user can either type the address of the page into the browser's address bar or click a link in the current page that specifies the next page to load. In either case, the web browser builds a request for the web page and sends it to the web server. This request, known as an HTTP request, is formatted using the HyperText Transfer Protocol (HTTP), which lets the web server know which file is being requested. ‘When the web server receives the HTTP request, it retrieves the requested file from the disk drive. This file contains the HTML (HyperText Markup Lan= ‘guctge) for the requested page. Then, the web server sends the file back to the browser as part of an HTTP response ‘When the browser receives the HTTP response, it renders (translates) the HTML into a web page that is displayed in the browser. Then, the user can view the content. Ifthe user requests another page, either by clicking a link or typing another web address into the browser's address bar, the process begins again. Chapter 1 Introduction to web development A static web page at http://www.modulemedia.com/ourwork/index.html (Ss Swat dg aio pn ie pp HPT Acie OR ee ew HB Dieses arta ne in | 62 emanate “9 Dt o> modulemedia ore About Gur Work Tang og) Contact | Our clients love working with us and we love our clients Sect case stds Web Browser Web Server (HTML files) Description Hypertext Markup Language (HTML) is the language used to design the web pages ofan application, A static web page is an HTML document that’s stored on the web server and doesn't change. The filenames for static web pages have .htm or html extensions. © When the user requests a static web page, the browser sends an HTTP request to the web server that includes the name ofthe file that’s being requested. ‘© When the web server receives the request, it retrieves the HTML for the web page and sends it back to the browser as part of an HTTP response. © When the browser receives the HTTP response, it renders the HTML into a webs page that is displayed in the browser. Figure 1-2 How static web pages are processed Section 1 JavaSeript essemtials How dynamic web pages are processed Addynamic web page like the one in figure 1-3 is a page that’s created by a program or script on the web server each time it is requested. This program or script is executed by an application server based on the data that's sent along with the HTTP request. In this example, the HTTP request identified the book that’s shown, Then, the program or script retrieved the image and data for that, book from a database server The diagram in this figure shows how a web server processes a dynamic web page. The process begins when the user requests a page in a web browser. To do that, the user can either type the URL of the page into the browser’s address bar, click a link that specifies the dynamic page to load, or click a button that submits a form that contains the data that the dynamic page should process. In each case, the web browser builds an HTTP request and sends it to the web server. This request includes whatever data the application needs for pro- cessing the request. If, for example, the user has entered data into a form, that data will be included in the HTTP request. ‘When the web server receives the HTTP request, the server examines the file extension of the requested web page to identify the application server that should process the request. The web server then forwards the request to the application server that processes that type of web page. Next, the application server retrieves the appropriate program or script from the hard drive. Italso loads any form data that the user submitted. Then, it executes the script. As the script executes, it generates the HTML for the web page. If necessary, the script will request data from a database server and use that data as part of the web page itis generating, The processing that’s done on the application server can be referred to as server-side processing. ‘When the script is finished, the application server sends the dynamically generated HTML back to the web server. Then, the web server sends the HTML back to the browser in an HTTP response. ‘When the web browser receives the HTTP response, it renders the HTML and displays the web page. Note, however, that the web browser has no way to tell whether the HTML in the HTTP response was for a static page or a dynamic page. Itjust renders the HTML. ‘When the page is displayed, the user can view the content. Then, when the user requests another page, the process begins again. The process that begins with the user requesting a web page and ends with the server sending a response back to the client is called a round trip, Chapter 1 Introduction to web development A dynamic web page at amazon.com Off to Colle AMAZON serinssncon naxadeae orcas Hip ween xemsioe __Nuracs HTMLS and CSS9 Papatack Seas atc! | CB) — main ten el annem: © ee a Sct How a web server processes a dynamic web page Web Browser Web Server Application Server Database Server (Scripts) Description © Adynamic web page is a web page that’s generated by a program or seript that is, running on a server. © When a web server receives a request fora dynamic web page, it looks up the extension of the requested file to find out which application server should process the request. ‘© When the application server receives a request, it runs the specified script. Often, this script uses the data that it gets from the web browser to get the appropriate data from adatabase server. This script can also store the data that it receives in the database. ‘© When the application server finishes processing the data, it generates the HTML for a web page and returns it to the web server, Then, the web server returns the HTML. to the web browser as part of an HTTP response. Figure 1-3 How dynamic web pages are processed 10 Section 1 JavaSeript essemtials How JavaScript and jQuery are used for client-side processing In contrast to the server-side processing that's done for dynamic web pages, JavaScript isa scripting language that provides for client-side processing In the ‘web page in figure 1-4, for example, JavaScript is used to change the images that are shown without using server-side processing. To make this work, all of the required images are loaded into the browser when the page is requested. Then, if the user clicks on one of the color swatches below a shirt, the shirt image is changed to the one with the right color. This is called an image swap Similarly, if the user moves the mouse over a shirt, the image is replaced by a close-up image of the shirt. This is called an image rollover. The diagram in this figure shows how JavaScript processing works. When a browser requests a web page, both the HTML and the related JavaScript are returned to the browser by the web server. Then, the JavaScript code is executed in the web browser by the browser's JavaScript engine, This takes some of the processing burden off the server and makes the application run faster. Often, JavaScript is used in conjunction with dynamic web pages, but itis also com- monly used with static web pages. Besides image swaps and rollovers, there are many other uses for JavaScript. For instance, another common use is to validate the data that the user enters into an HTML form before itis sent to the server for processing, This saves unneces- sary trips to the server. Other common uses of JavaScript are to run slide shows and carousels and to provide data in tabs or accordions. Where does jQuery fit into this picture? jQuery is actually a JavaScript library, which means that itis JavaScript, Today, because jQuery makes it easier to develop many common JavaScript applications, jQuery is the most popular JavaScript library. That's why the last four sections in this book are devoted to teaching you how to get the most from jQuery. Chapter 1 Introduction to web development — 14 b page with image swaps and rollovers Casares 7 aoa Boys’ Big Kd VNec Tops eer oor oro _E __ Image = a rollover | Sm eT a! H - 7 el a Image ee swap | a How JavaScript fits into this architecture HTTP request HTTP response (with HTML and savaScrip) Web Browser Web Server (JavaScript engine) (HTML and JavaScript files) Three of the many uses of JavaScript and jQuery © Data validation © Image swaps and rollovers Slide shows Description © JavaScripts a scripting language that is run by the JavaScript engine of a web browser and controls the operation of the browser. © jQueryis a JavaScript library that makes it easier to do many of the functions that JavaScript can be used for. ‘© When the browser requests an HTML page that contains JavaScript ora link to a JavaScript file, both the HTML and the JavaScript are loaded into the browser. © Because JavaScript runs on the client, not the server, its functions don’t require a trip back to the server. This helps an application run more efficiently. Figure 1-4 How JavaScript and jQuery are used for client-side processing 12 Section 1 JavaSeript essemtials The components of a JavaScript application ‘When you develop a JavaScript application, you use HTML to define the content and structure of the page. You use CSS to format that content. And you use JavaScript to do the client-side processing. This is illustrated by the Email List application that is presented next. How the Em: List application works Figure 1-5 presents the user interface for an Email List application, It asks the user to make three entries and then click on the Join our List button, The asterisks to the right of the text boxes for the entries indicate that these entries are required. ‘When the user clicks on the button, JavaScript checks the entries to make sure they're valid, If they are, the entries are sent to the web server for server side processing, If they aren't, messages are displayed so the user can correct the entries. This is a common JavaScript application called data validation that saves atrip to the server when the entries are invalid. The HTML HyperText Markup Language (HTML) is used to define the content and structure of a web page. In figure 1-5, you can see the HTML for the Email List. application. In general, this book assumes that you are already familiar with HTML, but here are a few highlights. First, note that this document starts with a DOCTYPE declaration, This dec Jaration is the one you'll use with HTMLS, and you must code it exactly as it’s shown here, If you aren’t already using HTMLS, you can see that this declaration is much simpler than the declaration for earlier versions of HTML. In this book, all of the applications use HTMLS. Second, in the head section of the HTML document, you can see a meta ele- ‘ment that specifies that UTF-8 is the character encoding that’s used for the page. You can also see a link element that specifies the CSS file that should be used to format this HTML. And you can see a script element that specifies the JavaScript file that should be used to process the user's entries. Third, in the body section, you can see the use of a section element, That is one of the HTMLS elements that we'll be using throughout this book. Within this section, you can see the use of hl, form, label, input, and span elements. In this book, as you've just seen, we refer to HTML elements like the , <
Please join our email list
or a closing tag like . The CSS Not long ago, HTML documents were coded so the HTML not only defined the content and structure of the web page but also the formatting of that content. However, this mix of structural and formatting elements made it hard to edit, maintain, and reformat the web pages. Today, Cascading Style Sheets (CSS) let you separate the formatting from the content and structure of a web page. As a result, the formatting that was once done with HTML should now be done with CSS. In figure 1-6, then, you can see the CSS that’s used to format the HTML in figure 1-5, Here again, this book assumes that you are already familiar with CSS, bbut here is a quick description of what this CSS is doing. In the rule set for the body element, the font-family property sets the font for the entire document, the margin property centers the body in the browser wine dow, the width property sets the width of the body to 650 pixels, and the border property puts a blue border around the body. This is typical CSS for the applica tions in the book, just to make them look better. Similarly, the rule sets forthe hl, section, label, and input elements are intended to make these elements look better. Here, the rule set for the hl element sets the font color to blue, And the rule set for the section puts some space (pad- ding) between the section contents and the right, bottom, and left border. ‘Next, the rule set for the labels floats them left so the text boxes will be to their right. This rule set also sets the width of the labels to lem, and aligns the text forthe labels on the right. Then, the rule set for the input elements sets the left margin so there's space between the labels and the text boxes, and it sets the bottom margin so there's space after each label and text box. Last, the rule set for the span elements sets the text color to red. When the HTML page is first loaded, these span elements only contain asterisks (*). But the JavaScript changes that if one or more of the entries are invalid. Chapter 1 Introduction to web development Please join our email list Email Address: Reenter EmailAddess SSS irs Name [sein cru] The link element in the HTML file that applies the CSS file The code for the CSS file named email_list.css body ( font-family: Arial, Helvetica, sans-serif; background-color: white; margil auto; width: 650px; border: 3px solid blue; al ( color: blue; ? section ( padding: 0 2em lem; ? label ( float: left; width: Liem; text- aan ( ‘color: red; } Description © Cascading Style Sheets (CSS) are used to control how web pages are displayed by specifying the fonts, colors, borders, spacing, and layout of the pages. Figure 1-6 The CSS for the web page 15 16 Section 1 JavaSeript essemtials The JavaScript Figure 1-7 shows how this application looks in a browser if the JavaScript finds any invalid data after the user clicks the Join our List button, Here, you can see that error messages are displayed to the right of the user entries for the second and third text boxes. In other words, the JavaScript has actually changed the contents of the span elements. ‘When JavaScript changes the HTML for a page, it is called DOM scripting. ‘That's because the JavaScript is actually changing the Document OL ject Model (or DOM) that’s generated by the browser when the page is loaded. This DOM represents all of the elements and attributes that are coded in the HTML. Then, when JavaScript changes any aspect of the DOM, the change is immediately made to the browser display too. After the browser display, this figure shows the JavaScript for this applica. tion. Since you are going to learn how all of this code works in the next two chapters, you may want to skip over this code right now, But if you have any programming experience, it may be worth taking a quick look at it. In that case, here are a few highlights. To start, this code consists of three functions: a $ function, a joinList fune- tion that is executed when the user clicks on the button, and a function that is run after the DOM has been loaded into the browser. Then, in the joinList function, ‘you can see four if-else statements that provide most of the logic for this application, Here, you can see that the if-else structures are similar to those in any mod~ ern programming language like Java, C#, or PHP. You can also see that declar- ing a variable (var) and assigning a variable is done in a way that’s similar to the ‘way that’s done in other programming languages. ‘What's different about JavaScript is that it provides methods and properties that let you modify the DOM. For instance, the $ function uses the getElement Byld method to get the object with the id that’s passed to the function. The first statement in the joinList function, for example, uses the $ function to get the object that represents the first text box in the HTML. Then, this statement uses the value property to get the value that the user entered into that text box. Later, in the first if statement, if that value is an empty string (*”), which ‘means the user didn't make an entry, the JavaScript replaces the * in the span element for that text box with an error message. To do that, it uses this code: $("email_addressi_error").firstChild.nodeValue = “This field is required."; Although this code may look daunting right now, you'll see that it’s all quite manageable. You'll also come to realize that DOM scripting is where JavaScript (and jQuery) get their power. Chapter 1 Introduction to web development — 17 The web page in a browser with JavaScript used for data validation (© oe Email List - Mozilla Firefox 608 mania Please join our email list Email Address: zak@yahoocom Reenter EmailAddess: ———~=~S~S*ST ity must equal fst erty irs Name “This fied is required. The script element in the HTML file that includes the JavaScript file The code for the JavaScript file named email_list.js var § = function (id) ( return document .getElementByra(id); > var joinbist = function () ( var emailaddress1 = §("email_addressi") value; var emailAddress2 = §("email_address2") var isValid = if (gmailaddressi ==") ( $("email_address1_error").firstChild.nodevalue = oT isvalid ) else { §("email address _error").firstChild.nodeValue = "*; ) if (emailAddress] !== emailAddress2) { $("email_address2_error").fi Th: st equal first entry."; isvalid ) else { §("email address? error").firstChild.nodevalue = ""; } Af ($("first_name").value ==") ( $("first_name_error").firstChild.nodeValue = ) else ( §("first_name error").firstChild.nodeValue = if (isvalia) ( // submit the form if all entries are valid $(temail_form").submit (); > window.onload = function () ¢ $(*Join_list").onclick = joinbist; $("email_address").focus Figure 1-7 The JavaScript for the web page 18 Section 1 JavaSeript essemtials The HTML and CSS skills that you need for this book Although this book assumes that you are already familiar with HTML and the next six topics present a quick review of the HTML and CSS skills that you're going to need for this book. If you don't already have these skills and you can't pick them up from the topics that follow, we recommend that you use Murach’s HTMLS and CSS3as a reference while you're learning JavaScript and jQuery. How to use the HTML5 semantic elements All of the applications in this book use the HTMLS semantic elements when- ever they're appropriate. If you aren't already using them or at least familiar with them, figure I-8 summarizes what you need to know. In particular, the applications in this book use the section, aside, and nav elements, That makes it easier to apply CSS to these elements because you don’t have to code id attributes that are used by the CSS. Instead, you can apply the CSS to the elements themselves. Be aware, however, that older browsers won't recognize the HTMLS seman- tic elements, which means that you wor't be able to use CSS to apply formatting to them, So, if you want your CSS to work in older browsers, you need to code a script element in the head section of the HTML document that provides a JavaScript shiv (also known as a shim), This shiv uses JavaScript to put the HTMLS elements in the DOM, which makes the browser aware of them. ‘The script element in this figure is one that you can use in all of your HTML pages. It gets the shiv froma Google web site and loads it into the browser. To wwe space and repetition, we don’t always show this script element in the appl+ ations in this book, but it is used in all of the downloadable applications. Chapter 1 Introduction to web development — 19) The primary HTMLS semantic elements Element Contents header The header fora page. section A generic section of a document that doesn’t indicate the type of content. article A composition like an article in the paper. nav A section of a page that contains links to other pages or placeholders, aside A section of a page like a sidebar that is related to the content that’s near it figure ‘An image, table, or other component that's treated asa figure. footer The footer for a page. The JavaScript shiv that tells older browsers about the HTMLS5 elements A page that’s structured with header, section, and footer elements
San Joaquin Valley Town Hall

Welcome to San Joaquin Valley Town Hall. We have some fascinating speakers for you this season!

kcopy; San Joaquin Valley Town Hall.

The page displayed in a web browser San Joaquin Valley Town Hall ‘Welcome to San Joaquin Vey Town Hall We have some fstnating speakers for souls season! (© San Joaquin Vasey Toon Hal Description © HTMLS provides new semantic elements that you should use to structure the contents of a web page. Using these elements can be referred to as HTMLS semantics. «All of the HTMLS elements in ths figure are supported by the modern browsers. They will also work on older browsers if you include the JavaScript shiv shown above in the head section of the HTMLS document. Besides the HTMLS semantic elements, this book uses standard HTML elements. like headings (hl and h2 elements), images (img elements), links ( elements), and paragraphs (

elements). Figure 1-8 How to use the HTMLS semantic elements 20 Section 1 JavaSeript essemtials How to use the div and span elements If you've been using HTML fora while, you are certainly familiar with the div element, It has traditionally been used to divide an HTML document into divisions that are identified by id attributes, Then, CSS can use the ids to apply formatting to the divisions. But now that HTMLS is available, div elements shouldn't be used to struc- ture a document. Instead, they should only be used when the HTMLS semantic elements aren't appropriate. Note, however, that div elements are often used in JavaScript applications. If, for example, a section element contains three h2 elements with each followed by a div element, JavaScript can be used to display or hide a div element whenever the heading that precedes it is clicked, This structure is illustrated by the first example in figure 1-9, and you'll see how this works in chapter 6. Similarly, span elements have historically been used to identify portions of text that can be formatted by CSS. By today’s standards, though, its better to use elements that indicate the contents of the elements, like the cite, code, and elements. But here again, span elements are often used in JavaScript applications, as shown by the second example in this figure, In fact, you've just seen this in the Email List application. In that application, JavaScript puts the error messages in the appropriate span elements. Chapter 1 Introduction to web development — 24 The div and span elements EES aiv ‘block element that provides a container for other elements span An inline element that lets you text that ean be formatted with CSS. Div elements in the HTML for a JavaScript application

jquery FAQs 11 contents eyakes

why is jQuery becoming so popular?

11 contents eyakes

which is harder to learn: jQuery or JavaScript?

aia 11 contents yates
Span elements in the HTML for a JavaScript application Kapaa Td="email_addressl_erroc*>*
Kapaa id=ensii_sddress?_error'>*
Kepan ids"Grst_nane error*>* Description © Before HTMLS, div elements were used to define the structure within the body of a document. The ids for these div elements were then used by the CSS to apply formatting to the elements. * Now, the HTMLS semantic elements are replacing div elements. That makes the structure of a page more apparent, However, you will still use div elements to define blocks of code that are used in some JavaScript applications. «Before HTMLS, span elements were used to identify portions of text that you could apply formatting to. Today, a better practice is to use specific elements to identify content. However, you will still use span elements for some JavaScript applications like the application in figures 1-5 through 1-7. Figure 1-9 How to use the div and span elements 22 Section 1 JavaSeript essemtials How to use the basic HTML attributes Figure 1-10 presents the HTML attributes that are commonly used in JavaScript applications. You should already be familiar with the id attribute that identifies one HTML element and with class attributes that can be applied to more than one HTML element. You should also be familiar with the title attr- bute that can he used to provide a tooltip for an element and with the for attribute that relates a label to an input element. ‘When you use JavaScript, you will commonly use the id attribute to get or set the data in an input element. You will commonly use the name attribute so the server-side code can access the data that is submited to it. You will some- times add or remove class attributes to change the formatting of elements. And ‘you will sometimes use title attributes to provide text thats related to elements. In practice, you usually use the same value for the id and name attributes of an element, For instance, the example in this figure uses “email” as the value of both the id and name attributes. That makes it easier to remember the attribute values. Chapter 1 Introduction to web development 28 The basic HTML attributes ESE) Specifies a unique identifier for an element that can be referred to by CSS. Specifies one or more class names that can be referred to by CSS, and the same name can be used for more than one element, To code more than one class name, separate the class names with spaces, Specifies addtional information about an element, For some elements, the title appears ina tooltip when the user hovers the mouse over the element Ina label element, this attribute specifies the id of the control that it applies to Specifies a unique name for an element that is commonly used by the server- side code and can also be used by the JavaScript code. HTML that uses these attributes San Joaquin Valley Town Hall

Please enter your e-mail address to subscribe to our newsletter.

The HTML in a web browser with a tooltip displayed for the text box San Joaquin Valley Town Hall Welcome to San Joaquin Valley Town Hall. ‘Please enter your e-mail address to subscube fo ou newsletter: E-Mait Subscibe Entre mal adeesshere Description * Anatiribute consists of an attribute name, an equals sign, and the value of the attri- bute enclosed in either single or double quotation marks. © The id and class attributes are commonly used to apply CSS formatting, The name attribute is commonly used by the server-side code to access the data that is sent to it, but this attribute can also be used by the JavaScript code for a page. © The for attribute in a label element is used to identify the control that it applies to. Figure 1-10 How to use the basic HTML attributes. 24 Section 1 JavaSeript essemtials How to provide CSS styles for an HTML page Figure I-11 shows the two ways that styles are included for an HTML page in the applications in this book. First, you can code a link element in the head section of an HTML document that specifies a file that contains the CSS for the page. This is referred to as an external style sheet, and this is the method that's used for most of the applications in this book. Second, you can code a style element in the head section that contains the CSS for the page. This can be referred to as embedded styles The benefit of using embedded styles is that you don’t have to switch back and forth between HTML and CSS files as you develop a page. Overall, though, i's better to use external style sheets because that makes it easier to use them for more than one page. In some cases, you may want to use two or more external style sheets for a single page, You may even want to use both external style sheets and embedded styles for a page. In these cases, the styles are applied from the first external style sheet to the last one and then the embedded styles are applied. If you want to provide an external style sheet for printing a page, you can code the media attribute in the link element, Then, when the user prints the page, the styles in that style sheet override the screen styles, This lets you provide the right formatting for printed pages. Chapter 1 Introduction to web development — 25 Two ways to provide styles Use an external style sheet by coding a link element in the head section Embed the styles in the head section The sequence in which styles are applied Styles from an external style sheet Embedded styles A head element that includes two external style sheets San Joaquin Valley Town Hall The sequence in which styles are applied From the first external style sheet to the last How to specify the medium that an external style is for The Speaker Lineup

October 19: Jeffrey Toobin

Novenber 16: Andrew Ross Sorkin

Copyright SV Town Hall

CSS rule sets that select by element type, id, and class Three elements by type body { font-family: Arial, Helvetica, sans-serif; width: 400px; margin: lem auto; } section ( border: 2px solid black; padding: p ( margii jem; ) -25em 0 .25em 3em; ) One element by ID #first_heading { margin: 0 lem .25em; } Elements by class «blue { color: blue; } tright ( text-align: right; } The elements displayed in a browser The Speaker Lineup October 19: Jeffrey Toobin November 16; Andrew Ross Sorkin ‘Copyiight SIV Town Hall Description © You code a selector forall elements of a specific type by naming the element. This is referred to as a type selector © You code an id selector for an element with an id attribute by coding a pound sign (followed by the id value. This is known as anid selector © You code a selector for an element with a class attribute by coding a period followed by the class name. Then, the rule set applies to all elements with that class name. This is known as a class selector Figure 1-12 _ How to code the basic CSS selectors 28 Section 1 JavaSeript essemtials How to code CSS rule sets Figure 1-13 presents the CSS for the Email List application that was pre- sented earlier in this chapter. This is typical of the CSS for the applications in this book. Since the focus of this book is on JavaScript and jQuery, not CSS, the CSS is usually limited, For instance, the CSS in this example doesn’t require id or class selectors. Just to make sure we're using the same terminology, this CSS contains seven rule sets. Each rule set consists of a selector, a set of braces { }, and one or more rules within the braces. Also, each rule consists of a property name, a colon, the value or values for the rule, and an ending semicolon. ‘The first rule set in this example applies to the seven HTMLS semantic ele rents, Itis required for compatibility with older browsers. It tells those browsers that the semantic elements should be treated as block elements. Without this rule set, older browsers will treat these elements as inline elements, which is not what you want. Although this rule set won't be shown in the CSS for the applications for this book, itis included with the downloadable applications. As a result, those appli- cations should run on older browsers. Beyond that, this book will explain any of the CSS that is relevant to the JavaScript for an application, So for now, if you know how to code rule sets, you're ready to continue. Chapter 1 Introduction to web development The CSS file for a typical application in this book /* The C88 workaround so the HTMLS semantic ¢: article, aside, figure, footer, header, nav, section ( display: block; } body ( font-family: Arial, Helvetica, sans-serif; background-color: ‘whites margin: 0 auto; width: 650px; border: 3px solid blue; } an ¢ color: blue; } section ( padding: 0 2em tem; } Label ( oat: lest; width: idem; text-align: right; } input { margin-left: lem; margin-bottom: .Sem; } span {( color: red; } Description ‘© Because the focus of this book is JavaScript and jQuery, not CSS, the CSS that’s used in this book is usually simple. We just apply enough CSS to make each appli- cation look okay and work correctly. ‘© In fac, for most of the applications in this book, you won't have to understand the CSS so it won't even be shown. Whenever the CSS is critical to the understanding of the JavaScript application, though, it will be explained in detail. Atthe least, you should know that the CSS for an HTML document consists of one or more rule sets. Each of these rule sets starts with the selector for the rule set followed by a set of braces { }. Within the braces are one or more rules. # You should also know that each CSS rule consists of aproperty name, colon, the value or values for the property, and a semicolon, Figure 1-13 How to code CSS rule sets. ments can be formatted */ 29 30 Section | JavaScript essentials How to test a JavaScript application Next, you'll learn how to test a JavaScript application, To do that, you run the HTML for the web page that uses the JavaScript. How to run a JavaScript application ‘When you develop a JavaScript application, you're usually working on your ‘own computer or your company’s server, Then, to run the application, you use one of the four methods shown in figure I-14, Of the four, it’s easiest to run the HTML page from the IDE that you're using to develop the HTML, CSS, and JavaScript files. You'll learn more about that ina moment. In the first of the four methods in this fist list, Fil-9Open File means to drop down the File mena from the menu bar and select the Open File command. Similarly, File 9New-Web Project means to drop down the File menu, select the New command, and then select the Web Project command. This notation is used throughout this book. After an application has been uploaded to an Internet server, you can use the second set of methods in this figure to run the application, The first way is to enter a Uniform Resource Locator (URL) into the address bar of your browser. The second way is to click on a link on a web page that requests another page. You can also use this method iff an application is running on your own computer or server. As the diagram in this figure shows, the URL for an Internet page consists of, four components, In most cases, the protocol is HTTP. If you omit the protocol, the browser uses HTTP as the default. ‘The second component is thedomain name that identifies the web server that the HTTP request will be sent to. The web browser uses this name to look up the address of the web server for the domain, Although you can’t omit the domain name, you can often omit the “www.” from the domain name. The third component is the path where the fie resides on the server, The path lists the folders that contain the file, Forward slashes are used to separate the names in the path and to represent the server's top-level folder at the start of the path, In this example, the path is “fourwork/”. The last component is the name of the file. In this example, the file is named index.html If you omit the filename, the web server will search for a default doc- ument in the path. Depending on the web server, this file will be named index. html, default.htm, or some variation of the two. Chapter 1 Introduction to web development — 34 The web page at c:/jquery/book_apps/ch01/email_list.html GrEca Please join our email list Email Adress: Re-onter Email Adress: ist Name Four ways to run an HTML page that’s on your own server or computer Use the File Open command with Internet Explorer or the File->Open File command with Firefox. © If you're using Windows, find the file in the Windows Explorer and double-click on it. Use the features of your text editor or IDE. Click on a link in the current web page to load the next web page. ‘Two ways to run an HTML page that's on the Internet # Enter the URL of a web page into the browser's address bar. Click ona link in the current web page to load the next web page. The components of an HTTP URL on the Internet http: //www.modulemedia.com/ourwork/index.html A Dn protocol ‘domain name path filename What happens if you omit parts of a URL Ifyou omit the protocol, the default of http:// will be used. Ifyou omit the filename, the default document name for the web server will be used. This is typically index.html, default.htm, or some variation, Description © When you are developing JavaScript applications, you usually store them on your ‘own computer instead of the Internet. So when you test the applications, you run them from your own computer. Later, after the applications are deployed to your Internet web server, you can run the applications from the Internet. Figure 1-14 How to run a JavaScript application 32 Section 1 JavaSeript essemtials How to ensure cross-browser compatibility If you want your web site to be used by as many visitors as possible, you need to make sure that your web pages are compatible with as many browsers as possible, That's known as cross-browser compatibility. That means you should test your applications on as many browsers as possible, including the five browsers summarized in figure 1-15, as well as the older versions of those browsers. ‘The table in this figure shows the current release numbers of these browsers and their rating for HTMLS support. To get an updated version of this informa- tion, though, you can go to the web site at . This web site will also rate the browser that you're using when you access it. In general, Internet Explorer (IE) gives web developers the most problems because it’s the least standard. In contrast, the other four browsers generally support the same features so if a web page runs on one of them, it will also run on the others, The other four browsers also provide for automatic updates, but IE typically hasn't done that, As a result, the other four browsers are most likely to support the latest features of HTMLS and CSS3. Incidentally, IE not only has some HTML and CSS incompatibilities, but also some JavaScript incompatibilites. In fact, one of the benefits of using {Query is that its functions have already been tested for cross-browser compat ibility, As a result, they will work on all browsers. To provide for browsers that don’t support the HTMLS and CSS3 features that are presented in this book, you need to use the workarounds shown in this figure, However, its difficult to test your web pages in older browsers because (1) you can’t get them anymore and (2) you can’t put all versions of the old browsers on one system even if you could get them. If you're a student, you probably won't need to test your web pages on old browsers. But for production applications, that type of testing is essential. To help you do it, you can search the Internet for web sites or software products that provide ways to test your pages on old browsers. To do the exercises in this book, you can get by with just the current ver sions of IE and Firefox. But if you're using a Mac OS system, you won't be able to install IE so you can skip any steps that require it or substitute Safari for IE references. For a production system, of course, you need to install all five brows- ers and make sure your web pages work on all of them. Chapter 1 Introduction to web development 38 The current browsers and their HTMLS ratings (perfect score is 500) Browser ee) Google Chrome Opera Movilla Firefox Apple Safari Internet Explorer The web site for these ratings Guidelines for cross-browser compatibility Test your web pages on all of the major browsers, including all of the older versions of these browsers that are still commonly used. Use the HTMLS and CSS3 features that are supported by all of the modern brows- ers, which are the features that are presented in this book. But use the workarounds. so these applications will run on the older browsers too. The two workarounds for using the HTMLS5 semantic elements The JavaScript shiv that lets older browsers know about the elements The CSS rule set that sets the semantic elements to block elements article, aside, figure, figcaption, footer, header, nav, section ( display: block; } How to test your web pages in older browsers ‘© One of the problems in cross-browser testing is that you can't install all of the old browsers on one system. In particular, Windows doesn’t let you install more than one version of IE at the same time. The solution is to use programs or web sites that offer this type of testing. To find out what's available, try searching for “browser testing software” or “cross browser testing”. Description © Today, there are still differences in the way that different browsers handle HTML, CSS, and JavaScript. As a developer, though, you want your web pages to work on as many different web browsers as possible, This is referred to as cross-browser compatibility. © One of the benefits of using jQuery is that it provides cross-browser compatibility for the JavaScript that it provides. However, the HTML, CSS, and other JavaScript can still cause compatibility problems. ‘In general, Internet Explorer gives web developers the most problems because it is, the least standard and hasn't provided for automatic updates. Eventually, all browsers will support HTMLS and C883 so the workarounds won't be necessary. Figure 1-15 How to ensure cross-browser compatibility 34 Section | JavaScript essemtals How to use Aptana to develop JavaScript applications Because HTML, CSS, and JavaScript are just text, you can use any text edi tor to create the files fora JavaScript application, However, a better editor or an Integrated Development Environment (IDE) can speed development time and reduce coding errors. That's why we recommend Aptana Studio 3. It isa free IDE that runs on Windows, Mac OS, and Linux, and it can greatly improve your productivity. In the appendix for this book, you can learn how to install Aptana, You can also learn how to use Aptana for the common development functions in the top- ics that follow. If you prefer to use another editor, of course, you can skip these topics. But even then, you may want to browse these topics because they will give you a good idea of what an IDE should be able to do. They may also encour age you to give Aptana a try. How to create a project In Aptana, a prcject consists of the folders and files for a complete web application, Once you create a project, i's easier to work with its folders and files, to create new files for the project, and so forth. To create a project, you use the procedure in figure 1-16. The result of this procedure is that you end up with a named project that starts with the top-level folder for the application. Then, you can easily access the folders and files for the application by using the App Explorer window that’s shown in the next figure. To make it easier to work with the applications for this book, we recommend that you create an Aptana project that includes all of them. To do that, you can create a project named jQuery Book Apps that starts with the path shown in this figure. The final dialog box for doing this is displayed in this figure. Chapter 1 Introduction to web development The last dialog box for creating an Aptana project Bia 2 EBOum0- BE%-0- l4~ (ReAppeplors Ei] Pajecttioe| GY 5) See cene ner pe Prpctnme suey pe Lectin Soe AN hese sherri eC eer [ene cn an a ee a9 he ee are The folder that contains the folders for all of the book applications c:\murach\jquery\book_apps How to create a project © Use the File 3New-9Web Project command to display the New Web Project dialog box that’s shown above. Or, in the App Explorer window, click on the Create Project button, select Web Project in the dialog box that’s displayed, and click the Next button to display the New Web Project dialog box. Inthe New Web Project dialog box, enter a name for the project. Next, uncheck the Use Default Location box, click on the Browse button, and select the top-level folder for the project. «Read the warning message that appears so you realize that deleting the project in ‘Aptana may also delete the project on the disk drive. Then, click the Finish button. Description ‘© Aptana works the best when you set up projects for the web applications that you're developing and maintaining. © Ingeneral, each Aptana prc ect should contain the folders and files for one web application. For the purposes of this book, however, you can set up one project for all of the book applications, one project forall of the exercises, and one project for all of the exercise solutions. Figure 116 How to create a project in Aptana 36 Section 1 JavaSeript essemtials How to open or close an HTML, CSS, or JavaScript file Figure 1-17 shows how to open or close an HTML, CSS, or JavaScript file after you've created a project. Here, the jQuery Book Apps project is shown in the App Explorer window on the let side of Aptana, If you have created more than one project, you can switch from one to another by using the drop-down project list that’s at the top of the App Explorer window. Once you have the correct project open, you can drill down to the file that ‘you want to open by clicking on the plus signs for the folders. In this example, the ch0l and email_list folders have been expanded so you can see the four files for the Email List application. Then, to open a file, you just double-click on it. ‘When you open file in Aptana, itis opened in a new tab. This means that you can have several files open at the same time and move from one to another bby clicking on a tab. This makes it easy to switch back and forth between the HTML, CSS, and JavaScript files for a web page. This also makes it easy to copy code from one file to another. If you want to open a file that isn't part of a project, you can do that by using one of the methods shown in this figure, First, you can use the Project Explorer ‘window to locate the file on your computer and then double-click on it. Second, you can use the File->Open File command to open a file. To close one or more files, you can use one of the three methods shown in this figure, This makes it easy to close all of the files except the ones that you're currently working with, And that helps you avoid the mistake of making a change to the wrong file. As you work with Aptana, you'll see that it has the same type of interface that you've used with other programs. So if you want to do something that isn't presented in this chapter, try right-clicking on an item to see what menu options are available. Check out the other buttons in the toolbar. See what's available. from the drop-down menus, With a little experimentation, you'll find that this program is not only powerful, but also easy to use. Chapter 1 Introduction to web development 37. Aptana with the App Explorer shown and a JavaScript file in the second tab [Ewe Bok pps Olena lami atom ud tc sete ape ieee BEO- SaS-O- M\¥- SE owe) ee. (ermten. o[Sretn|=O |e lama] =5 GMs >> | Dar Stanton (a) : Ei 2 Te eturm caret grtlenentsI4(i0);, {Oey Books = thar Jouniise = function (( areal ladaresst > $¢ sae T & ar eraladares 5 ar fevalld = tres yaret Binns Boer Boa P Oine % [eB Ssmpls| He = = yeti tee | adress? error") firetChild.nedeale 8 @ onus rave"). <=“) ¢ aero) Flrstehik.ndevelue = “his fielé valid = false, 2 How to open a file within a project ¢ Use the drop-down list in Aptana’s App Explorer to select the project. © Then, locate the file in the App Explorer and double-click on it. ‘Two ways to open an HTML file that isn’t in a project Use the Project Explorer to locate the file, and double-click on it. Use the File Open File command. How to close one or more files © To close one file, click on the X in the tab for the file. # To close all of the files except one, rightclick on the tab you don’t want to close and select Close Others. © To close all of the files, right click on any tab and select Close All. Description ‘¢ When you open a file, the file is displayed in a new tab. Figure 1-17 How to open or close an HTML, CSS, or JavaScript file in Aptana 38 Section | JavaScript essentials How to change the colors that highlight the syntax ‘When you opena file in Aptana, one of the first things you might want to do is change the colors that are used to highlight the syntax of HTML, CSS, and JavaScript code, That’s because the default settings are light colors on a dark background that can be hard to read. To change the colors, you can use the procedure in figure 1-18, In this book, we use the Dreamweaver theme, but you can experiment with other themes until you find one that you like. If you click the Apply button after you select a theme, you can see the colors that are used in the window behind the dialog box. Then, if you like the colors, you can click the OK button to close the dialog box. Chapter 1 Introduction to web development —— 39 Aptana’s Themes dialog box ‘ypefita tet ‘Themes Or ory Genet plana Sto comm (Geammsnstscas) (2) fers) [inven [pen] a : Ferma Epes Lire : aseret eb ne ne ohh (a) = tering Ts bie E ns Mac Classic jw 2 Gama Mee Tene ee alata 2 Pastels on Dark a Ii) Vataason em Z cy Web Sevee E Ravowe fF - fe reaps = ie Rrvbeon Toon = fam ~ = itoplt tinen stud) views App taal on St) eon top estaronto view Procedure Use the Window Preferences command to open the Preferences dialog box. Click on Aptana Studio, and then click on Themes to display the Themes dialog box. © Choose a theme from the drop-down list. Description ‘© Aptana displays different parts of the JavaScript statement in different colors so the statements are easier to interpret. Ifyou don’t like the colors that are used, you can change the colors by using the procedure above. Figure 1-18 How to change the colors that highlight the syntax in Aptana 40 Section 1 JavaSeript essemtials How to edit a file Figure 1-19 shows how to edit a JavaScript file with Aptana, but editing ‘works the same for HTML and CSS files. When you open a file with an html, css, or js extension, Aptana knows what type of file you're working with so it ean use color to highlight the syntax components, The good news is that color coding is also used for CSS that’s ina style element of an HTML document or JavaScript that’s in a script element of an HTML document. As you entera new line of code, the auto-completion feature presents lists of ‘words that start with the letters that you've entered. This type of list is illustrated by this figure. Here, the list shows the JavaScript choices after the letter r has been entered, Then, you can select a word and press the Tab key to insert it into your code. This also works with HTML and CSS entries. If, for example, you type Open File command to open this HTML file: ¢:\murach\jquery\book_apps\ch0l\email_list\index.html To test what happens when you don’t enter any data, just click the Join our L button without entering any data, Then, you can see the error messages that are displayed. 3. _Enteran email address in the first text box and invalid data in the second text box and click the Join our List button to see what error messages are displayed. 4. Enter valid data for all three text boxes and click on the button. Then, the data is submitted for processing and a new web page is displayed. Exercise 1-2 Run other section 1 applications This exercise has you run the applications presented in chapter 6, These applications will give you some idea of what you'll able to do when you complete this section. Open this file in the Firefox browser: ¢:\murach\jquery\book_apps\ch06\faqs_links\index.html Then, click on one of the headings to display the text for it, and click the heading again to hide the text. 6. Open this file in the Firefox browser: ¢:\murach\jquery\book_apps\ch06\image_swap\index.html ‘Then, click on the small images to see the large image get swapped. 7. Open this file in the Firefox browser: ¢:\murach\jquery\book_apps\ch06\slide_show\index.html Watch the slide show. Chapter 1 Introduction to web development Exercise 1-3 Get started with Aptana This exercise is for readers who are going to use Aptana with this book. It guides you through the process of creating projects that provide easy access to the book applications and exercises that you've downloaded. Create the projects 1. Start Aptana, and use the procedure in figure 1-16 to create a project for the book applications that are stored in this folder: ¢:\murach\jquery\book_apps This project should be named jQuery Book Apps, and the entries for the last dialog box should be just like those in this figure. 2. Use the same procedure to create a project named jQuery Exercises for the exercises that are stored in this folder: cr\Jquery\exercises as well as a project named jQuery Solutions for the exercise solutions that are stored in this folder: #\murach\jquery\solutions ‘Test the Email List application 3. Use the drop-down list in the App Explorer to select the jQuery Exercises project. This provides access to all of the exercises that are inthis book. 4. Click on the plus sign before ch01 to display the email_list folder, and click on the plus sign for the email_list folder to display the files for the Email List application. 5. Double-click on the file named index.htm! to open that file, Then, click the Run button in the toolbar to run the application in the default browser. That will automatically switch you to that browser. 6. Switch back to Aptana, and click on the down arrow to the right of the Run button, Ifthe drop-down list offers Internet Explorer, click on it to run the application in that browser. Then, return to Aptana. Edit the JavaScript code 7. Inthe App Explorer, double click on the file named email_li file, and note the colors that are used for syntax highlighting, 8. If you don’t like the colors that are used, use the procedure in figure 1-18 to change them. js to open that 9. Inthe JavaScript file, delete the right parenthesis in the first line of code. This should display two error markers. Then, hover the mouse over the markers to display the error descriptions. This illustrates Aptana’s error-checking feature. Now, undo the change that you made. (To undo a change with the keyboard, press Ctrl+Z.) 47 48 Section 1 JavaSeript essemtials 10. lL. 12. 13. In the JavaScript file, after the third statement that starts with var, start a ‘statement on a new line with these characters: if (e This should display alist of the possible entries that start with the letter e. Here, you can see that email Address| and emailAddress? are included in the list. These are the variables that are created by the first two var statements, and this illustrates Aptana's code-completion feature, Now, undo this change. Enter this statement on a new line that comes right before the last Line of the JavaScript code, which consists of justa right brace (}): alert("The DOM has now been built"); In other words, this statement will become the second last line in the file. To test the statement that you've added, click on the Save All button in the toolbar to save your changes. Then, switch to your browser and click on the Reload or Refresh button to run the application with this change. This should display a dialog box that you can close by clicking on its OK button, After that, the application should work the same as it did before. If you're curious, do more experimenting on your own, Then, close the files and exit from Aptana, Getting started with JavaScript ‘The goal of this chapter is to get you off to a good start with JavaScript, especially if you're new to programming. If you have programming experience with another language, you should be able to move rapidly through this chapter. Otherwise, take it easy and do the exercises at the end of this chapter. How to include JavaScript in an HTML document. ‘Two ways to include JavaScript inthe head of an HTML document. How to include JavaScript in the body of an HTML document. How to create identifiers. How to use comments. How to use objects, methods, and properties. How to work with JevaSeript date. ‘The primitive datatypes. How to code numeric expressions nn How to work with numeric variables. nnn How to work with string and Boolean Variable in How to use the parselnt and parseFloat methods. How to code control statements.. How to code conditional expressions. How to code if statements. How to code while and do-while loops. How to code for loops. ‘Two illustrative applications. ‘The Miles Per Gallon application. ‘The Test Scores application, How to find errors in your code. How to get ertor messages with Firefox. 50 Section 1 JavaSeript essemtials How to include JavaScript in an HTML document In chapter 1, you saw how the JavaScript for an application can be coded in a separate file, But there are actually three different ways to include JavaScript in an HTML document. You'll learn all three now. Two ways to include JavaScript in the head of an HTML document Figure 2-1 presents two of the three ways to include JavaScript in an HTML document. As you saw in the last chapter, one way is to code the JavaScript in a separate external fle. Then, you code a script element in the head section of the HTML document to include that file. In the script element, the sre attribute is used to refer to the external file. For this element, you can also code a type attribute with the value “text/javascript” to tell the browser what kind of content the file contains. But with HTMLS, that attribute is no longer needed because the assumption is that all files that are referred to in script elements contain JavaScript. In the example in ths figure, the stc attribute refers toa file named caleu- Jate_mpgjs. The assumption here is that this fie is inthe same folder as the HTML file. Otherwise, you need to code a relative URL that provides the right path for the file. If, for example, the JavaScript file is in a folder named javascript and that folder is in the same folder as the HTML file, the sre attribute would be coded this way: This works the same as it does for any other file reference in an HTML document. The second way to include JavaScript in an HTML document is to code the JavaScript within the script element in the head section, This can be referred to as embedded JavaScript. Note, however, that the application will work the same whether the JavaScript is embedded in the head section or loaded into the head section from an external file. The benefit of using an external file is that it separates the JavaScript from the HTML. The benefit of using embedded JavaScript is that you don't have to switch between the HTML and JavaScript files as you develop the application, In the examples in this book, you'll see both uses of JavaScript. Chapter? Getting started with JavaScript 51 ‘Two attributes of the script element CESS Specifies the location and name of an external JavaScript file. With HTMLS, this attribute can be omitted. If you code it, use “text/javascript” for JavaScript code. A script element in the head section that loads an external JavaScript file A script element that embeds JavaScript in the head section ad> Description © A script element in the head section of an HTML document is commonly used to identify an external JavaScript file that should be included with the page. A script element in the head section can also contain the JavaScript statements that are included with the page. This can be referred to as embedded JavaScript. * Ifyou code more than one script element in the head section, the JavaScript is included in the sequence in which the script statements appear. ‘© When a script element in the head section includes an external JavaScript fle, the JavaScript in the file runs as if it were coded in the script element. Figure 2-1 Two ways to include JavaScript in the head of an HTML document Section 1 JavaSeript essemtials How to include JavaScript in the body of an HTML document Figure 22 shows a third way to include JavaScript in an HTML document. This time, the two script elements in the first example are coded in the body of. the HTML document. When a script element is coded in the body, the element is replaced by the output of the JavaScript code when the application is loaded. If you want to provide for browsers that don't have JavaScript enabled, you can code a noscript element after a script element as shown in the second exam ple. Then, if JavaScript is disabled, the content of the noscript element will be displayed. But if JavaScript is enabled, the script element is replaced by the out- put of the JavaScript code and the noscript element is ignored. This way, some output will be displayed whether or not JavaScript is enabled. In the second example, the noscript element is coded right after a script element, so 2012 will replace the output ofthe script element if JavaScript isn’t enabled in the browser, This means that the result will be the same in the year 2012 whether or not JavaScript is enabled, But in the year 2013, the year will be updated by the JavaScript if it is enabled. You can also code a noscript element that doesn’t follow a script element, For instance, you can code a noscript element atthe top of a page that warns the user that the page won't work right if JavaScript is disabled. This is illustrated by the third example, In this case, nothing is displayed if JavaScript is enabled and the message is displayed if JavaScript is disabled. Inail of the applications in this book, the JavaScript is either embedded in the head section of the HTML or in an external fie that’s identified in the head section of the HTML. However, you shouldn't have any trouble including the JavaScript in the body of an HTML document whenever you want to do that. Chapter? Gening started with JavaSeripn 5B JavaScript in the body of an HTML document

©senbsp; » San Joaquin Valley Town Hall

The result of the JavaScript in a web browser Current date: Mon Mar 12 2012 © 2012, San Joaquin Valley Town Hall” A noscript element in the body of an HTML document

kcopysénbsp; » San Joaquin Valley Town Hall

A noscript element at the start of an HTML document

Description © Ifa script element is coded in the body of a document, it is replaced by the output of the JavaScript code. © The noscript element can be used to display content when JavaScript is disabled in a user's browser. Figure 22 Howto include JavaScript in the body of an HTML document 54 Section | JavaScript essentials The JavaScript syntax The syntaxof JavaScript refers to the rules that you must follow as you code statements. If you don't adhere to these rules, your web browser won't be able to interpret and execute your statements. How to code JavaScript statements Figure 2-3 summarizes the rules for coding JavaScript statements. The first rule is that JavaScript is case-sensitive. This means that uppercase and lower- case letters are treated as different letters, For example, the names salestax and salesTax are treated as different words. The second rule is that JavaScript statements must end with a semicolon. If you don’t end each statement with a semicolon, JavaScript won't be able to tell where one statement ends and the next one begins. ‘The third rule is that JavaScript ignores extra whitespace in statements. Since whitespace includes spaces, tabs, and new line characters, this lets you break long statements into multiple lines so they're easier to read. Be careful, though, to follow the guidelines in this figure about where to splita statement. If you don‘ spit a statement at a good spot, JavaScript will sometimes try to help you out by adding a semicolon for you, and that can lead to errors. Getting started with JavaScript 55 A block of JavaScript code var jointist = function () ( var emailAddressi = §("email_addressi").value; var emailaddress? = §("email_address2") value if (enailaddressi r¢ alert ("Email Address is required."); ) else if (emailaddress2 == **) ( alert ("Second Email Address is required."); if (emailaddressi !== emailaddress2) ( alert ("Second Email entry must equal first entry. ) else if (S(*first_name").value == "") ( alert ("First Name is required."); ) else ¢ $("email_form"). submit (); del d ? The basic syntax rules # JavaScript is case-sensitive. © JavaScript ignores extra whitespace within statements. © Each JavaScript statement ends with a semicolon. How to split a statement over two or more lines © Splita statement after: ~ anarithmetic or relational operator such as +, -%/ = an opening brace ( { ), bracket ([), or parenthesis = aclosing brace ( } ) >,or< © Do not split a statement after: ~ an identifier, a value, or the return keyword = aclosing bracket (] ) or parenthesis Description © A JavaScript statement has a syntax that’s similar to the syntax of Java. © Whitespace refers to the spaces, tab characters, and return characters in the code, and it is ignored by the compiler. As a result, you can use spaces, tab characters, and return characters to format your code so its easier to read. © Insome cases, JavaScript will try to correct what it thinks is a missing semicolon by adding a semicolon at the end of a split line. To prevent this, follow the guide lines above for spitting a statement, Figure 2-3 How to code JavaScript statements 56 Section 1 JavaSeript essemtials How to create identifiers Variables, functions, objects, properties, methods, and events must all have names so you can refer to them in your JavaScript code, An identifiers the name given to one of these components. Figure 2-4 shows the rules for creating identifiers in JavaScript. Besides the first four rules, you can't use any of the JavaScript reserved words (also known as keywords) as an identifier. These are words that are reserved for use within the JavaScript language, You should also avoid using any of the JavaScript global properties or methods as identifiers, which you'll learn more about as you prog- ress through this book. Besides the rules, you should give your identifiers meaningful names. ‘That means that it should be easy to tell what an identifier refers to and easy to remember how to spell the name, To create names like that, you should avoid abbreviations. If, for example, you abbreviate the name for monthly investment ‘as mon_iny, it will be hard to tell what it refers to and hard to remember how you spelled it, Bu if you spell it out as monthly_ investment, both problems are solved. Similarly, you should avoid abbreviations that are specific to one industry or field of study unless you are sure the abbreviation will be widely understood. For example, mpg is a common abbreviation for miles per gallon, but cpm could stand for a number of different things and should be spelled out. To create an identifier that has more than one word in it, many JavaScript programmers use a convention called camel casing With this convention, the first letter of each word is uppercase except for the first word, For example, monthlyinvestment and taxRate are identifiers that use camel casing. The alternative is to use underscore characters to separate the words in an identifier, For example, monthly_ investment and tax_rate use this convention. If the standards in your shop specify one of these conventions, by all means use it Otherwise, you can use whichever convention you prefer..but be consistent. In this book, we use underscore notation for the ids and class names in the HTML and camel casing for all JavaScript identifier. That way, it will be easier for you to tell where the names originated.

You might also like