Beginning JavaScript
5/5
()
About this ebook
Beginning JavaScript 5th Edition shows you how to work effectively with JavaScript frameworks, functions, and modern browsers, and teaches more effective coding practices using HTML5. This new edition has been extensively updated to reflect the way JavaScript is most commonly used today, introducing you to the latest tools and techniques available to JavaScript developers. Coverage includes modern coding practices using HTML5 markup, the JSON data format, DOM APIs, the jQuery framework, and more. Exercises with solutions provide plenty of opportunity to practice, and the companion website offers downloadable code for all examples given in the book.
- Learn JavaScript using the most up to date coding style
- Understand JSON, functions, events, and feature detection
- Utilize the new HTML5 elements and the related API
- Explore new features including geolocation, local storage, and more
JavaScript has shaped the Web from a passive medium into one that is rich, dynamic, and interactive. No matter the technology on the server side, it's JavaScript that makes it come alive in the browser. To learn JavaScript the way it's used today, Beginning JavaScript, 5th Edition is your concise guide.
Related to Beginning JavaScript
Related ebooks
JavaScript for Beginners Rating: 5 out of 5 stars5/5Build Your Own Website The Right Way Using HTML & CSS: Start Building Websites Like a Pro! Rating: 3 out of 5 stars3/5PHP jQuery Cookbook Rating: 0 out of 5 stars0 ratingsJavaScript: Novice to Ninja Rating: 4 out of 5 stars4/5Coding For Kids: JavaScript Adventures with 50 Hands-on Activities Rating: 0 out of 5 stars0 ratingsjQuery: Novice to Ninja: Novice to Ninja Rating: 4 out of 5 stars4/5JavaScript from Zero to Proficiency (Beginner): JavaScript from Zero to Proficiency, #1 Rating: 0 out of 5 stars0 ratingsThe Best Javascript Rating: 0 out of 5 stars0 ratingsJavaScript Bible Rating: 4 out of 5 stars4/5Designing the Internet of Things Rating: 3 out of 5 stars3/5Programming the BeagleBone Black: Getting Started with JavaScript and BoneScript Rating: 0 out of 5 stars0 ratingsBreaking the Code: Five Steps to a Life-Changing Software Development Job Rating: 5 out of 5 stars5/5Python Rating: 0 out of 5 stars0 ratingsUnity Essentials: Your First Steps in Game Development: Unity Game Development Series Rating: 0 out of 5 stars0 ratingsSoftware Developer Rating: 0 out of 5 stars0 ratingsProgramming Pioneer Ada Lovelace Rating: 0 out of 5 stars0 ratingsLÖVE for Lua Game Programming Rating: 5 out of 5 stars5/5Code the Classics Volume II Rating: 0 out of 5 stars0 ratingsDrupal 8 Configuration Management Rating: 0 out of 5 stars0 ratingsEldarlands LARP Player's Handbook Rating: 0 out of 5 stars0 ratingsRaspberry Pi Projects for Kids - Second Edition Rating: 4 out of 5 stars4/5PHP BLUEPRINT: An Essential Beginners Guide to Learn the Realms of PHP From A-Z Rating: 0 out of 5 stars0 ratingsMastering MCP Server Architecture: A Complete Guide to Building a Modular Command Protocol Server from Scratch Rating: 0 out of 5 stars0 ratingsProgramming for Everyone Rating: 3 out of 5 stars3/5ESP32 Arduino Programming Handbook: Microcontroller Programming Series Rating: 0 out of 5 stars0 ratingsThe Official Raspberry Pi Projects Book Volume 4: 200 Pages of Inspiration and Ideas. 55 Projects & Guides Rating: 0 out of 5 stars0 ratingsCrossing Wires: Making Sense of Technology, Transhumanism, and Christian Identity Rating: 5 out of 5 stars5/5C++ Programming: From Novice to Expert in a Step-by-Step Journey Rating: 0 out of 5 stars0 ratingsRaspberry Pi Gaming - Second Edition Rating: 0 out of 5 stars0 ratings
Programming For You
iOS 26 App Development Essentials - SwiftUI Edition: Developing iOS 26 Apps using SwiftUI, Swift and Xcode 26 Rating: 0 out of 5 stars0 ratingsLearn SAP BI in 24 Hours Rating: 3 out of 5 stars3/5PHP, MySQL, & JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5PowerShell 7 for IT Professionals Rating: 1 out of 5 stars1/5Programming in Python: Learn the Powerful Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsProxmox Administration Essentials: Definitive Reference for Developers and Engineers Rating: 0 out of 5 stars0 ratingsSAP Service Management - Advanced Configuration Guide 2 Rating: 0 out of 5 stars0 ratingsThe Book of Powershell Rating: 0 out of 5 stars0 ratingsCreating ELearning Games with Unity Rating: 0 out of 5 stars0 ratingsLearning LEGO MINDSTORMS EV3 Rating: 5 out of 5 stars5/5PHP & MySQL Practice It Learn It Rating: 4 out of 5 stars4/5Swipe This!: The Guide to Great Touchscreen Game Design Rating: 4 out of 5 stars4/5JavaScript Made Easy: A Beginner's Practical Guide to Coding Interactive Web Pages Rating: 0 out of 5 stars0 ratingsUnity Multiplayer Games Rating: 5 out of 5 stars5/5Excel VBA Programming: Task Optimization and Daily Work Automation Rating: 0 out of 5 stars0 ratingsOntotext GraphDB in Practice: The Complete Guide for Developers and Engineers Rating: 0 out of 5 stars0 ratingsLearn to Code with Scratch: Let Your Kids' Creative Ideas Come to Life by Coding Them into Programs Rating: 0 out of 5 stars0 ratingsGood Luck Have Fun: The Rise of eSports Rating: 3 out of 5 stars3/5Beginning Programming with Java For Dummies Rating: 5 out of 5 stars5/5Python For Kids For Dummies Rating: 0 out of 5 stars0 ratingsMinecraft: 70 Top Minecraft Mods That Your Friends Do Not Know (But Wish They Did!) Rating: 4 out of 5 stars4/5Hacking Android Rating: 5 out of 5 stars5/5Web Designer's Idea Book, Volume 4: Inspiration from the Best Web Design Trends, Themes and Styles Rating: 4 out of 5 stars4/5
Reviews for Beginning JavaScript
1 rating0 reviews
Book preview
Beginning JavaScript - Jeremy McPeak
INTRODUCTION
JAVASCRIPT IS A SCRIPTING LANGUAGE that enables you to enhance static web applications by providing dynamic, personalized, and interactive content. This improves the experience of visitors to your site and makes it more likely that they will visit again. You must have seen the flashy drop-down menus, moving text, and changing content that are now widespread on websites—they are enabled through JavaScript. Supported by all the major browsers, JavaScript is the language of choice on the web. It can even be used outside web applications—to automate administrative tasks, for example.
This book aims to teach you all you need to know to start experimenting with JavaScript: what it is, how it works, and what you can do with it. Starting from the basic syntax, you’ll move on to learn how to create powerful web applications. Don’t worry if you’ve never programmed before—this book will teach you all you need to know, step by step. You’ll find that JavaScript can be a great introduction to the world of programming: with the knowledge and understanding that you’ll gain from this book, you’ll be able to move on to learn newer and more advanced technologies in the world of computing.
WHO THIS BOOK IS FOR
To get the most out of this book, you’ll need to have an understanding of HTML, CSS, and how to create a static web page. You don’t need to have any programming experience.
This book will also suit you if you have some programming experience already and would like to turn your hand to web programming. You will know a fair amount about computing concepts, but maybe not as much about web technologies.
Alternatively, you may have a design background and know relatively little about the web and computing concepts. For you, JavaScript will be a cheap and relatively easy introduction to the world of programming and web application development.
Whoever you are, I hope that this book lives up to your expectations.
WHAT THIS BOOK COVERS
You’ll begin by looking at exactly what JavaScript is, and taking your first steps with the underlying language and syntax. You’ll learn all the fundamental programming concepts, including data and data types, and structuring your code to make decisions in your programs or to loop over the same piece of code many times.
Once you’re comfortable with the basics, you’ll move on to one of the key ideas in JavaScript—the object. You’ll learn how to take advantage of the objects that are native to the JavaScript language, such as functions, dates, and strings, and find out how these objects enable you to manage complex data and simplify your programs. Next, you’ll see how you can use JavaScript to manipulate and detect objects made available to you in the browser and detect the browsers.
From here, you’ll move on to more advanced topics, such as writing code to dynamically manipulate elements within a web page and executing code when certain things happen within your page. You’ll also learn how to script forms and other controls. Using this knowledge, you can start to create truly professional-looking applications that enable you to interact with the user.
You’ll then learn how to store data within the browser and communicate directly with a server. You’ll also learn how to write code for the new HTML5 media elements, and write your own custom user interface for them.
You’ll explore some of the time saving JavaScript frameworks such as jQuery, Modernizr, Prototype, and MooTools and see how they work and how they can help you create sophisticated JavaScript powered applications.
Finally, you’ll look at common syntax and logical errors, how you can spot them, and how to use the JavaScript debuggers for Chrome, Internet Explorer, Firefox, Safari, and Opera to aid you with this task. Also, you need to examine how to handle the errors that slip through the net, and ensure that these do not detract from the experience of the end user of your application.
All the new concepts introduced in this book will be illustrated with practical examples, which enable you to experiment with JavaScript and build on the theory that you have just learned.
You’ll find four appendixes at the end of the book. Appendix A provides solutions to the exercises included at the end of most chapters throughout the book. The remaining appendixes contain the reference material that your authors hope you find useful and informational. Appendix B contains the JavaScript language’s core reference. Appendix C contains a complete W3C DOM Core reference—as well as information on the HTML DOM and DOM level 2 Event model. Appendix D contains the decimal and hexadecimal character codes for the Latin-1 character set.
WHAT YOU NEED TO USE THIS BOOK
Because JavaScript is a text-based technology, all you really need to create documents containing JavaScript is a text editor. Any will do.
Also, in order to try out the code in this book, you will need a web browser that supports a modern version of JavaScript. Ideally, this means the latest versions of Chrome, Internet Explorer, Firefox, Safari, and Opera. The book has been extensively tested with these browsers. However, the code should work in any modern web browser. Where there are exceptions, they will be clearly noted.
CONVENTIONS
To help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.
TRY IT OUT
The Try It Out is an exercise you should work through, following the text in the book.
It usually consists of a set of steps.
Each step has a number.
Follow the steps with your copy of the database.
As you work through each Try It Out, the code you’ve typed will be explained in detail.
WARNING Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.
NOTE Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
As for styles in the text:
We highlight in italic type new terms and important words when we introduce them.
We show keyboard strokes like this: Ctrl+A.
We show file names, URLs, and code within the text like so:
persistence.properties.
We present code in two different ways:
Important code in code examples is highlighted with a gray background.
The gray highlighting is not used for code that’s less important in the present context, or that has been shown before.
SOURCE CODE
As you work through the examples in this book, you may choose either to type in all the code manually or to use the source-code files that accompany the book. All of the source code used in this book is available for download at www.wrox.com. Once at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.
NOTE Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-1-118-90333-9.
Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.
You can also view the examples presented in this book at http://beginningjs.com.
ERRATA
We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time you will be helping us provide even higher-quality information.
To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.
If you don’t spot your
error on the Book Errata page go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.
P2P.WROX.COM
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system on which you can post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.
At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:
Go to p2p.wrox.com and click the Register link.
Read the terms of use and click Agree.
Complete the required information to join as well as any optional information you wish to provide, and click Submit.
You will receive an e-mail with information describing how to verify your account and complete the joining process.
NOTE You can read messages in the forums without joining P2P, but in order to post your own messages, you must join.
Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.
1
Introduction to JavaScript and the Web
WHAT YOU WILL LEARN IN THIS CHAPTER:
Adding JavaScript to your web pages
Referencing external JavaScript files
Changing the background color of a web page
WROX.COM CODE DOWNLOADS FOR THIS CHAPTER
You can find the wrox.com code downloads for this chapter at http://www.wiley.com/go/BeginningJavaScript5E on the Download Code tab. You can also view all of the examples and related files at http://beginningjs.com.
In this introductory chapter, you look at what JavaScript is, what it can do for you, and what you need in order to use it. With these foundations in place, you will see throughout the rest of the book how JavaScript can help you to create powerful web applications for your website.
The easiest way to learn something is by actually doing it, so throughout the book you create a number of useful example programs using JavaScript. This process starts in this chapter, by the end of which you will have created your first piece of JavaScript code.
INTRODUCTION TO JAVASCRIPT
In this section you take a brief look at what JavaScript is, where it came from, how it works, and what sorts of useful things you can do with it.
What Is JavaScript?
Having bought this book, you are probably already well aware that JavaScript is some sort of computer language, but what is a computer language? Put simply, a computer language is a series of instructions that tell the computer to do something. That something can be one of a wide variety of things, including displaying text, moving an image, or asking the user for information. Normally, the instructions, or what is termed code, are processed from the top line downward. This simply means that the computer looks at the code you’ve written, works out what action you want it to take, and then takes that action. The act of processing the code is called running or executing it.
In natural English, here are instructions, or code, you might write to make a cup of instant coffee:
Put coffee crystals in cup.
Fill kettle with water.
Put kettle on to boil.
Has the kettle boiled? If so, then pour water into cup; otherwise, continue to wait.
Drink coffee.
You’d start running this code from the first line (instruction 1), and then continue to the next (instruction 2), then the next, and so on until you came to the end. This is pretty much how most computer languages work, JavaScript included. However, on some occasions you might change the flow of execution or even skip over some code, but you see more of this in Chapter 3.
JavaScript is an interpreted language rather than a compiled language. What is meant by the terms interpreted and compiled?
Well, to let you in on a secret, your computer doesn’t really understand JavaScript at all. It needs something to interpret the JavaScript code and convert it into something that it understands; hence it is an interpreted language. Computers understand only machine code, which is essentially a string of binary numbers (that is, a string of zeros and ones). As the browser goes through the JavaScript, it passes it to a special program called an interpreter, which converts the JavaScript to the machine code your computer understands. It’s a bit like having a translator translate English to Spanish, for example. The important point to note is that the conversion of the JavaScript happens at the time the code is run; it has to be repeated every time this happens. JavaScript is not the only interpreted language; others exist, including PHP and Ruby.
The alternative compiled language is one in which the program code is converted to machine code before it’s actually run, and this conversion has to be done only once. The programmer uses a compiler to convert the code that he wrote to machine code, and this machine code is run by the program’s user. Compiled languages include C#, Java, and many others. Using a real-world analogy, it’s a bit like having a Spanish translator verbally tell you in English what a Spanish document says. Unless you change the document, you can use it without retranslation as much as you like.
Perhaps this is a good place to dispel a widespread myth: JavaScript is not the script version of the Java language. In fact, although they share the same name, that’s virtually all they do share. Particularly good news is that JavaScript is much, much easier to learn and use than Java. In fact, languages like JavaScript are the easiest of all languages to learn, but they are still surprisingly powerful.
JavaScript and the Web
For most of this book you look at JavaScript code that runs inside a web page loaded into a browser. All you need to create these web pages is a text editor—for example, Windows Notepad—and a web browser, such as Chrome, Firefox, or Internet Explorer (IE), with which you can view your pages. These browsers come equipped with JavaScript interpreters (more commonly known as JavaScript engines).
NOTE Throughout this book, we use the terms IE
and Internet Explorer
interchangeably when referring to Microsoft’s Internet Explorer browser.
In fact, the JavaScript language first became available in Netscape’s Navigator 2. Initially, it was called LiveScript, but because Java was the hot technology of the time, Netscape decided that JavaScript sounded more exciting. When JavaScript really took off, Microsoft decided to add its own dialect of JavaScript, called JScript, to Internet Explorer 3.
In 1997, JavaScript was standardized by Ecma International, a membership-based non-profit organization, and renamed to ECMAScript. Today’s browser makers look to the ECMAScript standard to implement the JavaScript engines included in their respective browsers, but that doesn’t necessarily mean that all browsers support the same features. JavaScript support among today’s browsers is certainly more unified than it has ever been, but as you see in future chapters, developers still have to cope with older, and in many cases non-standard, JavaScript implementations.
The ECMAScript standard controls various aspects of the language and helps ensure that different versions of JavaScript are compatible. However, although Ecma sets standards for the actual language, it doesn’t specify how it’s used in particular hosts. By host, we mean hosting environment; in this book, that is the web browser. Other hosting environments include PDF files, web servers, and many, many other places. In this book, we discuss only its use within the web browser. The organization that sets the standards for web pages is the World Wide Web Consortium (W3C). It not only sets standards for HTML and CSS, but also for how JavaScript interacts with web pages inside a web browser. You learn much more about this in later chapters of the book. Initially, you’ll look at the essentials of JavaScript before the more advanced stuff. In the appendices of this book, you’ll find useful guides to the JavaScript language and how it interacts with the web browser.
The majority of the web pages containing JavaScript that you create in this book can be stored on your hard drive and loaded directly into your browser from the hard drive itself, just as you’d load any normal file (such as a text file). However, this is not how web pages are loaded when you browse websites on the Internet. The Internet is really just one great big network connecting computers. Access to websites is a special service provided by particular computers on the Internet; the computers providing this service are known as web servers.
Basically, the job of a web server is to hold lots of web pages on its hard drive. When a browser, usually on a different computer, requests a web page contained on that web server, the web server loads it from its own hard drive and then passes the page back to the requesting computer via a special communications protocol called Hypertext Transfer Protocol (HTTP). The computer running the web browser that makes the request is known as the client. Think of the client/server relationship as a bit like a customer/shopkeeper relationship. The customer goes into a shop and says, Give me one of those.
The shopkeeper serves the customer by reaching for the item requested and passing it back to the customer. In a web situation, the client machine running the web browser is like the customer, and the web server providing the page requested is like the shopkeeper.
When you type an address into the web browser, how does it know which web server to get the page from? Well, just as shops have addresses, say, 45 Central Avenue, Sometownsville, so do web servers. Web servers don’t have street names; instead, they have Internet protocol (IP) addresses, which uniquely identify them on the Internet. These consist of four sets of numbers, separated by dots (for example, 127.0.0.1).
If you’ve ever surfed the Net, you’re probably wondering what on earth we’re talking about. Surely web servers have nice www.somewebsite.com names, not IP addresses? In fact, the www.somewebsite.com name is the friendly
name for the actual IP address; it’s a whole lot easier for us humans to remember. On the Internet, the friendly name is converted to the actual IP address by computers called domain name servers, which your Internet service provider will have set up for you.
What Can JavaScript Do for Me?
JavaScript is primarily used to interact with users. That’s a rather broad statement, so let’s break interact with users
into two categories: user input validation and enhancement.
JavaScript was originally created for validating form input. For example, if you had a form that takes a user’s credit card details in preparation for on online purchase of goods, you’d want to make sure he had actually filled in those details before you sent the goods. You might also want to check that the data being entered is of the correct type, such as a number for his age rather than text.
Thanks to the advances made in today’s JavaScript engines, JavaScript is used for much, much more than input-related tasks. In fact, advanced JavaScript-driven applications can be created that rival the speed and functionality of conventional desktop applications. Examples of such applications include Google Maps, Google Calendar, and even full-fledged productivity software such as Microsoft’s Office Web Apps. These applications provide a real service. In most of these applications, JavaScript only powers the user interface, with the actual data processing being done on the server. But even then, JavaScript could be used on the server if used with a JavaScript-based processing engine (one such environment is called Node).
Tools Needed to Create JavaScript Web Applications
The great news is that learning JavaScript requires no expensive software purchases; you can learn JavaScript for free on any PC or Mac. This section discusses what tools are available and how to obtain them.
Development Tools
All that you need to get started writing JavaScript code for web applications is a simple text editor, such as Notepad for Windows or TextEdit for Mac OS X. You can also use one of the many advanced text editors that provide line numbering, color coding, search and replace, and so on. Here are just a few:
Notepad2 (Windows):www.flos-freeware.ch/notepad2.html
WebMatrix (Windows):www.microsoft.com/web/webmatrix/
Brackets (Cross-Platform):brackets.io
Sublime Text (Cross-Platform):www.sublimetext.com
Sublime Text is not free software, but it does have a time-limited evaluation. If you try it and like it, please support the developers of that application.
You might also prefer a proper HTML editor; you’ll need one that enables you to edit the HTML source code, because that’s where you need to add your JavaScript. A number of very good tools specifically aimed at developing web-based applications, such as Adobe’s Dreamweaver, are also available. However, this book concentrates on JavaScript rather than any specific development tool. When it comes to learning the basics, it’s often best to write the code by hand rather than rely on a tool to do it for you. This helps you understand the fundamentals of the language before you attempt the more advanced logic that is beyond a tool’s capability. When you have a good understanding of the basics, you can use tools as timesavers so that you can spend time on the more advanced and more interesting coding.
Once you become more proficient, you may find that a web page editor makes life easier by inclusion of features such as checking the validity of your code, color-coding important JavaScript words, and making it easier to view your pages before loading them into a web browser. Many other, equally good, free web page editors are available. A Google search on web editing software will bring back a long list of software you can use.
As you write web applications of increasing complexity, you’ll find useful tools that help you spot and solve errors. Errors in code are what programmers call bugs, though when our programs go wrong, we prefer to call them unexpected additional features.
Very useful in solving bugs are development tools called debuggers. Debuggers let you monitor what is happening in your code as it’s running. In Chapter 18, you take an in-depth look at bugs and debugger development tools.
Web Browsers
In addition to software that lets you edit web pages, you’ll also need a browser to view your web pages. It’s best to develop your JavaScript code on the sorts of browsers you expect visitors to use to access your website. You see later in the chapter that although browsers are much more standards based, differences exist in how they view web pages and treat JavaScript code. All the examples provided in this book have been tested on Chrome, IE9-11, Firefox, Safari, and Opera. Wherever a piece of code does not work on any of these browsers, a note to this effect is made in the text.
If you’re running Windows, you’ll almost certainly have IE installed. If not, a trip to windows.microsoft.com/en-us/internet-explorer/download-ie will get you the latest version for your version of Windows.
You can find Chrome at www.google.com/chrome, and you can download Firefox at www.getfirefox.com.
By default, most browsers have JavaScript support enabled, but it is possible to disable this functionality in all browsers except Firefox. So before you start on your first JavaScript examples in the next section, you should check to make sure JavaScript is enabled in your browser.
To do this in Chrome, you want to modify the JavaScript settings in Content Settings, as shown in Figure 1.1. You can access these settings by navigating to chrome://settings/content or by following these instructions:
Go to the Settings option in the menu.
Click the Show advanced settings…
link.
Under Privacy, click the Content settings…
button.
Figure 1.1
It is harder to turn off scripting in Internet Explorer. Choose Internet Options from the menu (the gear icon in the upper-right corner), click the Security tab, and check whether the Internet or Local intranet options have custom security settings. If either of them does, click the Custom Level button and scroll down to the Scripting section. Check that Active Scripting is set to Enable.
A final point to note is how to open the code examples in your browser. For this book, you simply need to open the file on your hard drive in which an example is stored. You can do this in a number of ways, but the easiest is to just double-click the file.
WHERE DO MY SCRIPTS GO?
Inserting JavaScript into a web page is much like inserting any other HTML content; you use tags to mark the start and end of your script code. The element you use to do this is tag, is not HTML to be displayed, but rather script code to be processed. The chunk of code surrounded by the tags is called a script block. Here’s an example:
// JavaScript goes here
Basically, when the browser spots
You can put the
The
NOTE The element can be used for more than just JavaScript. Some JavaScript-based templating engines use elements to contain snippets of HTML.
Linking to an External JavaScript File
The
To link to an external JavaScript file, you need to create a
The web browser will read this code and include the file contents as part of your web page. When linking to external files, you must not put any code within the opening and closing
var myVariable;
if ( myVariable == 1 ) {
// do something
}
It’s important to note that an opening tag. You cannot use the self-closing syntax found in XML. Therefore, the following is invalid:
Generally, you use the www.mysite.com, the
Linking to an external file is common when incorporating well-known JavaScript libraries into a web page. The servers hosting these libraries are referred to as Content Delivery Networks, or CDNs. CDNs are relatively safe, but beware of linking to external files if they are controlled by other people. It would give those people the ability to control and change your web page, so you need to be very sure you trust them!
Advantages of Using an External File
The biggest advantage of external files is code reuse. Say you write a complex bit of JavaScript that performs a general function you might need in lots of pages. If you include the code inline (within the web page rather than via an external file), you need to cut and paste the code into each web page that uses it. This is fine as long as you never need to change the code, but the reality is you probably will need to change or improve the code at some point. If you’ve cut and pasted the code to 30 different web pages, you’ll need to update it in 30 different places. Quite a headache! By using one external file and including it in all the pages that need it, you need to update the code only once and all the 30 pages are updated instantly. So much easier!
Another advantage of using external files is that the browser will cache them, much as it does with images shared between pages. If your files are large, this could save download time and also reduce bandwidth usage.
YOUR FIRST SIMPLE JAVASCRIPT PROGRAM
Enough talk about the subject of JavaScript; let’s write some! We’ll start with a simple example that changes the background color of the web page.
TRY IT OUT Painting the Page Red
This is a simple example of using JavaScript to change the background color of the browser. In your text editor, type the following:
en>
utf-8 />
white>
Paragraph 1
document.bgColor = red
;
Save the page as ch1_example1.html to a convenient place on your hard drive, and load it into your web browser. You should see a red web page with the text Paragraph 1 in the top-left corner. But wait—don’t you set the tag’s BGCOLOR attribute to white? Okay, let’s look at what’s going on here.
The page is contained within and tags. This block contains a element. When you define the opening tag, you use HTML to set the page’s background color to white:
white>
Then you let the browser know that your next lines of code are JavaScript code by using the
Everything from here until the close tag, , is JavaScript and is treated as such by the browser. Within this script block, you use JavaScript to set the document’s background color to red:
document.bgColor = red
;
What you might call the page is known as the document for the purpose of scripting in a web page. The document has lots of properties, including its background color, bgColor. You can reference properties of the document by writing document, followed by a dot, followed by the property name. Don’t worry about the use of document at the moment; you look at it in greater depth later in the book.
Note that the preceding line of code is an example of a JavaScript statement. Every line of code between the tags is called a statement, although some statements may run on to more than one line.
You’ll also see that there’s a semicolon (;) at the end of the line. You use a semicolon in JavaScript to indicate the end of a statement. In practice, JavaScript is very relaxed about the need for semicolons, and when you start a new line, JavaScript will usually be able to work out whether you mean to start a new line of code. However, for good coding practice, you should use a semicolon at the end of statements of code, and a single JavaScript statement should fit onto one line rather than continue on to two or more lines. Moreover, you’ll find some situations in which you must include a semicolon, which you’ll come to later in the book.
Finally, to tell the browser to stop interpreting your text as JavaScript and start interpreting it as HTML, you use the script close tag:
You’ve now looked at how the code works, but you haven’t looked at the order in which it works. When the browser loads in the web page, the browser goes through it, rendering it tag by tag from top to bottom of the page. This process is called parsing. The web browser starts at the top of the page and works its way down to the bottom of the page. The browser comes to the tag first and sets the document’s background to white. Then it continues parsing the page. When it comes to the JavaScript code, it is instructed to change the document’s background to red.
WRITING MORE JAVASCRIPT
The first example let you dip your toes into the JavaScript waters. We’ll write a few more JavaScript programs to demonstrate the web page flow and one of the many ways to display a result in the browser.
TRY IT OUT Way Things Flow
Let’s extend the previous example to demonstrate the parsing of a web page in action. Type the following into your text editor:
en>
utf-8 />
white>
Paragraph 1
// script block 1
alert(First Script Block
);
Paragraph 2
// script block 2
document.bgColor = red
;
alert(Second Script Block
);
Paragraph 3
Save the file to your hard drive as ch1_example2.html and then load it into your browser. When you load the page, you should see the first paragraph, Paragraph 1, followed by a message box displayed by the first script block. The browser halts its parsing until you click the OK button. As you see in Figure 1.2, the page background is white, as set in the tag, and only the first paragraph is displayed.
Figure 1.2
Click the OK button, and the parsing continues. The browser displays the second paragraph, and the second script block is reached, which changes the background color to red. Another message box is displayed by the second script block, as shown in Figure 1.3.
Figure 1.3
Click OK, and again the parsing continues, with the third paragraph, Paragraph 3, being displayed. The web page is complete, as shown in Figure 1.4.
Figure 1.4
The first part of the page is the same as in our earlier example. The background color for the page is set to white in the definition of the tag, and then a paragraph is written to the page:
white>
Paragraph 1
The first new section is contained in the first script block:
// script block 1
alert(First Script Block
);
This script block contains two lines, both of which are new to you. The first line
// Script block 1
is just a comment, solely for your benefit. The browser recognizes anything on a line after a double forward slash (//) to be a comment and does not do anything with it. It is useful for you as a programmer because you can add explanations to your code that make it easier to remember what you were doing when you come back to your code later.
The alert() function in the second line of code is also new to you. Before learning what it does, you need to know what a function is.
Functions are defined more fully in Chapter 4, but for now you need only think of them as pieces of JavaScript code that you can use to do certain tasks. If you have a background in math, you may already have some idea of what a function is: it takes some information, processes it, and gives you a result. A function makes life easier for you as a programmer because you don’t have to think about how the function does the task—you can just concentrate on when you want the task done.
In particular, the alert() function enables you to alert or inform the user about something by displaying a message box. The message to be given in the message box is specified inside the parentheses of the alert() function and is known as the function’s parameter.
The message box displayed by the alert() function is modal. This is an important concept, which you’ll come across again. It simply means that the message box won’t go away until the user closes it by clicking the OK button. In fact, parsing of the page stops at the line where the alert() function is used and doesn’t restart until the user closes the message box. This is quite useful for this example, because it enables you to demonstrate the results of what has been parsed so far: The page color has been set to white, and the first paragraph has been displayed.
When you click OK, the browser carries on parsing down the page through the following lines:
Paragraph 2
// script block 2
document.bgColor = red
;
alert(Second Script Block
);
The second paragraph is displayed, and the second block of JavaScript is run. The first line of the script block code is another comment, so the browser ignores this. You saw the second line of the script code in the previous example—it changes the background color of the page to red. The third line of code is the alert() function, which displays the second message box. Parsing is brought to a halt until you close the message box by clicking OK.
When you close the message box, the browser moves on to the next lines of code in the page, displaying the third paragraph and, finally, ending the web page:
Paragraph 3
Another important point raised by this example is the difference between setting properties of the page, such as background color, via HTML and doing the same thing using JavaScript. The method of setting properties using HTML is static: A value can be set only once and never changed again by means of HTML. Setting properties using JavaScript enables you to dynamically change their values. The term dynamic refers to something that can be changed and whose value or appearance is not set in stone.
This example is just that, an example. In practice, if you want the page’s background to be red, simply set the background color with CSS (don’t use the bgcolor attribute in practice). Where you want to use JavaScript is where you want to add some sort of intelligence or logic to the page. For example, if the user’s screen resolution is particularly low, you might want to change what’s displayed on the page, and you can do that with JavaScript.
TRY IT OUT Displaying Results in a Web Page
In this final example, you discover how to write information directly to a web page using JavaScript. This proves more useful when you’re writing the results of a calculation or text you’ve created using JavaScript, as you see in the next chapter. For now, you’ll just write Hello World!
to a blank page using JavaScript:
en>
utf-8 />
results>
document.getElementById(results
).innerHTML = Hello World!
;
Save the page as ch1_example3.html to a convenient place on your hard drive. Now load it into your web browser and you’ll see Hello World! in the page. Although it would be easier to use HTML to do the same thing, this technique will prove useful in later chapters.
The first part of the page is the same as in our earlier examples, but things start to change when you reach this line:
results>
You’ll notice the
element has been given an ID using the id attribute. This ID must be unique in the web page, because it is used by JavaScript to identify the specific HTML element in the following line:
document.getElementById(results
).innerHTML = Hello World!
;
Don’t worry if this seems complex at the moment; you learn more about how this works in later chapters. Basically, the code is saying, Get me the element with the ID of results and set the HTML inside that element to Hello World!
It’s important in that the code accessing the paragraph is after the actual
element. Otherwise, the code would be attempting to access a paragraph before it existed in the page and would throw an error.
A BRIEF LOOK AT BROWSERS AND COMPATIBILITY PROBLEMS
In the preceding example you saw that by using JavaScript you can change a web page’s document background color using the bgColor property of the document. The example worked regardless of what browser you used because they all support a document with a bgColor property. You can say that the example is cross-browser compatible. However, it’s not always the case that the property or language feature available in one browser will be available in another browser. This is even sometimes the case between versions of the same browser.
One of the main headaches involved in creating web-based JavaScript is the differences between different web browsers, the level of HTML and CSS they support, and the functionality their JavaScript engines can handle. Each new release of any browser sees new and exciting features added to its HTML, CSS, and JavaScript support. The good news is that to a much greater extent than ever before, browser creators are complying with standards set by organizations such as Ecma and the W3C.
Which browsers you want to support really comes down to the browsers you think the majority of your website’s visitors—that is, your user base—will be using. This book is aimed at standards-compliant browsers, such as Chrome, IE9+, Firefox, Safari, and Opera.
If you want your website to be professional, you need to somehow deal with older browsers. You could make sure your code is backward compatible—that is, it only uses features available in older browsers. However, you may decide that it’s simply not worth limiting yourself to the features of older browsers. In this case you need to make sure your pages degrade gracefully. In other words, make sure that although your pages won’t work in older browsers, they will fail in a way that means the user is either never aware of the failure or is alerted to the fact that certain features on the website are not compatible with his or her browser. The alternative to degrading gracefully is for your code to raise lots of error messages, cause strange results to be displayed on the page, and generally make you look like an idiot who doesn’t know what he’s doing!
So how do you make your web pages degrade gracefully? You can do this by using JavaScript to determine which browser the web page is running in after it has been partially or completely loaded. You can use this information to determine what scripts to run or even to redirect the user to another page written to make best use of her particular browser. In later chapters, you see how to find out what features the browser supports and take appropriate action so that your pages work acceptably on as many browsers as possible.
SUMMARY
At this point, you should have a feel for what JavaScript is and what it can do. In particular, this brief introduction covered the following:
You looked into the process the browser follows when interpreting your web page. It goes through the page element by element (parsing) and acts upon your HTML tags and JavaScript code as it comes to them.
Unlike many programming languages, JavaScript requires just a text editor to start creating code. Something like Windows Notepad is fine for getting started, though more extensive tools will prove valuable once you get more experience.
JavaScript code is embedded into the web page itself, along with the HTML. Its existence is marked out by the use of
2
Data Types and Variables
WHAT YOU WILL LEARN IN THIS CHAPTER:
Representing data in code
Storing data in memory
Making calculations
Converting data
WROX.COM CODE DOWNLOADS FOR THIS CHAPTER
You can find the wrox.com code downloads for this chapter at http://www.wiley.com/go/BeginningJavaScript5E on the Download Code tab. You can also view all of the examples and related files at http://beginningjs.com.
One of the main uses of computers is to process and display information. By processing, we mean the information is modified, interpreted, or filtered in some way by the computer. For example, on an online banking website, a customer may request details of all money paid out from his account in the past month. Here the computer would retrieve the information, filter out any information not related to payments made in the past month, and then display what’s left in a web page. In some situations, information is processed without being displayed, and at other times, information is obtained directly without being processed. For example, in a banking environment, regular payments may be processed and transferred electronically without any human interaction or display.
In computing, information is referred to as data. Data comes in all sorts of forms, such as numbers, text, dates, and times, to mention just a few. In this chapter, you look specifically at how JavaScript handles data such as numbers and text. An understanding of how data is handled is fundamental to any programming language.
In this chapter you start by looking at the various types of data JavaScript can process. Then you look at how you can store this data in the computer’s memory so you can use it again and again in the code. Finally, you see how to use JavaScript to manipulate and process the data.
TYPES OF DATA IN JAVASCRIPT
Data can come in many different forms, or types. You’ll recognize some of the data types that JavaScript handles from the world outside of programming—for example, numbers and text. Other data types are a little more abstract and are used to make programming easier; one example is the object data type, which you won’t see in detail until Chapter 5.
Some programming languages are strongly typed. In these languages, whenever you use a piece of data, you need to explicitly state what sort of data you are dealing with, and use of that data must follow strict rules applicable to its type. For example, in a strongly typed language you can’t add a number and a word.
JavaScript, on the other hand, is a weakly typed language and a lot more forgiving about how you use different types of data. When you deal with data, you often don’t need to specify type; JavaScript will work that out for itself. Furthermore, when you are using different types of data at the same time, JavaScript will work out behind the scenes what it is you’re trying to do.
Given how easygoing JavaScript is about data, why talk about data types at all? Why not just cut to the chase and start using data without worrying about its type?
First of all, although JavaScript is very good at working out what data it’s dealing with, on occasion it’ll get things wrong or at least not do what you want it to do. In these situations, you need to make it explicit to JavaScript what sort of data type you intended and how it should be used. To do that, you first need to know a little bit about data types.
A second reason is that data types enable you to use data effectively in your code. The things that you can do with data and the results you’ll get depend on the type of data being used, even if you don’t explicitly specify what type it is. For example, although trying to multiply two numbers makes sense, doing the same thing with text doesn’t. Also, the result of adding numbers is very different from the result of adding text. With numbers you get the sum, but with text you get one big piece of text consisting of the other pieces joined together.
Let’s take a brief look at some of the more commonly used data types: numerical, text, and boolean. You see how to use them later in the chapter.
Numerical Data
Numerical data comes in two forms:
Whole numbers, such as 145, which are also known as integers. These numbers can be positive or negative and can span a very wide range in JavaScript: –2⁵³ to 2⁵³.
Fractional numbers, such as 1.234, which are also known as floating-point numbers. Like integers, they can be positive or negative, and they also have a massive range.
In simple terms, unless you’re writing specialized scientific applications, you’re not going to face problems with the size of numbers available in JavaScript. Also, although you can treat integers and floating-point numbers differently when it comes to storing them, JavaScript actually treats them both as floating-point numbers. It kindly hides the detail from you so you generally don’t need to worry about it. One exception is when you want an integer but you have a floating-point number, in which case you’ll round the number to make it an integer. You take a look at rounding numbers later in this chapter.
Text Data
Another term for one or more characters of text is a string. You tell JavaScript that text is to be treated as text and not as code simply by enclosing it inside quotation marks (). For example,
Hello World and
A are examples of strings that JavaScript will recognize. You can also use the single quotation marks ('), so 'Hello World' and 'A' are also examples of strings that JavaScript will recognize. However, you must end the string with the same quotation mark that you started it with. Therefore,
A' is not a valid JavaScript string, and neither is 'Hello World".
What if you want a string with a single quotation mark in the middle, say a string like Peter O'Toole? If you enclose it in double quotes, you’ll be fine, so Peter O'Toole
is recognized by JavaScript. However, 'Peter O'Toole' will produce an error. This is because JavaScript thinks that your text string is Peter O (that is, it treats the middle single quote as marking the end of the string) and falls over wondering what the Toole' is.
Another way around this is to tell JavaScript that the middle ' is part of the text and is not indicating the end of the string. You do this by using the backslash character (\), which has special meaning in JavaScript and is referred to as an escape character. The backslash tells the browser that the next character is not the end of the string, but part of the text. So 'Peter O\'Toole' will work as planned.
What if you want to use a double quote inside a string enclosed in double quotes? Well, everything just said about the single quote still applies. So 'Hello Paul
' works, but Hello
Paul won’t. However, Hello \"Paul\"
will work.
JavaScript has a lot of other special characters, which can’t be typed in but can be represented using the escape character in conjunction with other characters to create escape sequences. These work much the same as in HTML. For example, more than one space in a row is ignored in HTML, so a space is represented by the term . Similarly, in JavaScript you’ll find instances where you can’t use a character directly but must use an escape sequence. The following table details some of the more useful escape sequences.
The least obvious of these is the last, which represents individual characters by their character number in the Latin-1 character set rather than by their normal appearance. Let’s pick an example: Say you wanted to include the copyright symbol (©) in your string. What would your string need to look like? The answer is \xA9 Paul Wilton
.
Similarly, you can refer to characters using their Unicode escape sequence. These are written \uNNNN, where NNNN refers to the Unicode number for that particular character. For example, to refer to the copyright symbol using this method, you use the string \u00A9.
Boolean Data
The use of yes or no, positive or negative, and true or false is commonplace in the physical world. The idea of true and false is also fundamental to digital computers; they don’t understand maybes, only true and false. In fact, the concept of yes or no
is so useful it has its own data type in JavaScript: the boolean data type. The boolean type has two possible values: true for yes and false for no.
The purpose of boolean data in JavaScript is just the same as in the world outside programming: it enables you to answer questions and make decisions based on the answer. For example, if you are asked, Is this book about JavaScript?
you would hopefully answer, Yes it is,
or you might also say, That’s true.
Similarly, you might say, If it’s false that the subject of the book is JavaScript, then put it down.
Here you have a boolean logic statement (named after its inventor George Boole), which asks a question and then does something based on whether the answer is true or false. In JavaScript, you can use the same sort of boolean logic to give your programs decision-making abilities. You take a more detailed look at boolean logic in the next chapter.
VARIABLES—STORING DATA IN MEMORY
Data can be stored either permanently or temporarily.
You will want to keep important data, such as the details of a person’s bank account, in a permanent store. For example, when Ms. Bloggs takes ten dollars or pounds or euros out of her account, you want to deduct the money from her account and keep a permanent record of the new balance. Information like this might be stored in something called a database.
However, in other cases you don’t want to permanently store data, but simply want to keep a temporary note of it. Let’s look at an example. Say Ms. Bloggs has a loan from BigBank Inc., and she wants to find out how much is still outstanding on this loan. She goes to the online banking page for loans and clicks a link to find out how much she owes. This is data that will be stored permanently somewhere. However, suppose you also provide a facility for increasing loan repayments to pay off the loan early. If Ms. Bloggs enters an increased repayment amount into the text box on the web page, you might want to show how much sooner the loan will be paid. This will involve a few possibly complex calculations, so to make it easier, you want to write code that calculates the result in several stages, storing the result at each stage as you go along, before providing a final result. After you’ve done the calculation and displayed the results, there’s no need to permanently store the results for each stage, so rather than use a database, you need to use something called a variable. Why is it called a variable? Well, perhaps because a variable can be used to store temporary data that can be altered, or varied.
Another bonus of variables is that unlike permanent storage, which might be saved to disk or magnetic tape, variables are held in the computer’s memory. This means that it is much, much faster to store and retrieve the data.
So what makes variables good places for temporarily storing your data? Well, variables have a limited lifetime. When your visitors close the page or move to a new one, your variables are lost, unless you take some steps to save them somewhere.
You give each variable a name so that you can refer to it elsewhere in your code. These names must follow certain rules.
As with much of JavaScript code, variable names are case sensitive. For example, myVariable is not the same as myvariable. You’ll find that this is a very
