100% found this document useful (2 votes)
20 views

HTML5 programming with JavaScript for dummies Mueller - Download the ebook now and read anytime, anywhere

The document provides information on how to download the ebook 'HTML5 Programming with JavaScript For Dummies' by John Paul Mueller, along with links to other recommended programming ebooks. It includes details about the book's content, author, and publication information. Additionally, it features acknowledgments and a brief overview of the book's structure and chapters.

Uploaded by

samsaralerio
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
20 views

HTML5 programming with JavaScript for dummies Mueller - Download the ebook now and read anytime, anywhere

The document provides information on how to download the ebook 'HTML5 Programming with JavaScript For Dummies' by John Paul Mueller, along with links to other recommended programming ebooks. It includes details about the book's content, author, and publication information. Additionally, it features acknowledgments and a brief overview of the book's structure and chapters.

Uploaded by

samsaralerio
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Visit ebookfinal.

com to download the full version and


explore more ebooks or textbooks

HTML5 programming with JavaScript for dummies


Mueller

_____ Click the link below to download _____


https://ebookfinal.com/download/html5-programming-with-
javascript-for-dummies-mueller/

Explore and download more ebooks or textbook at ebookfinal.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Beginning Programming With Python For Dummies 1st Edition


John Paul Mueller

https://ebookfinal.com/download/beginning-programming-with-python-for-
dummies-1st-edition-john-paul-mueller/

LINQ For Dummies John Paul Mueller

https://ebookfinal.com/download/linq-for-dummies-john-paul-mueller/

Learn HTML5 and JavaScript for iOS 1st Edition Scott


Preston (Auth.)

https://ebookfinal.com/download/learn-html5-and-javascript-for-
ios-1st-edition-scott-preston-auth/

Microsoft Exchange Server 2007 For Dummies John Paul


Mueller

https://ebookfinal.com/download/microsoft-exchange-server-2007-for-
dummies-john-paul-mueller/
Beginning Programming with Java For Dummies Third Edition
Barry Burd

https://ebookfinal.com/download/beginning-programming-with-java-for-
dummies-third-edition-barry-burd/

Learn Unity3D Programming with UnityScript Unity s


JavaScript for Beginners 1st Edition Janine Suvak

https://ebookfinal.com/download/learn-unity3d-programming-with-
unityscript-unity-s-javascript-for-beginners-1st-edition-janine-suvak/

HTML5 For Dummies Quick Reference 1st Edition Andy Harris

https://ebookfinal.com/download/html5-for-dummies-quick-reference-1st-
edition-andy-harris/

HTML5 Game Development For Dummies 1st Edition Andy Harris

https://ebookfinal.com/download/html5-game-development-for-
dummies-1st-edition-andy-harris/

JavaScript Essentials for Dummies 1st Edition Paul


Mcfedries

https://ebookfinal.com/download/javascript-essentials-for-dummies-1st-
edition-paul-mcfedries/
HTML5 programming with JavaScript for dummies
Mueller Digital Instant Download
Author(s): Mueller, John Paul
ISBN(s): 9781118611883, 1118611888
Edition: Online-ausg
File Details: PDF, 19.68 MB
Year: 2013
Language: english
HTML5
Programming
with JavaScript ®

by John Paul Mueller


HTML5 Programming with JavaScript® For Dummies®
Published by
John Wiley & Sons, Inc.
111 River Street
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2013 by John Wiley & Sons, Inc., Hoboken, New Jersey
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permit-
ted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written
permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the
Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600.
Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley
& Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://
www.wiley.com/go/permissions.
Trademarks: Wiley, the Wiley logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!,
The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, Making Everything Easier, and
related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates
in the United States and other countries, and may not be used without written permission. JavaScript is
a registered trademark of Oracle America,Inc. All other trademarks are the property of their respective
owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO


REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS
OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING
WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY
MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND
STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS
SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL,
ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED,
THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE
PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT
THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR
A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE
PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR
RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET
WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS
WORK WAS WRITTEN AND WHEN IT IS READ.

For general information on our other products and services, please contact our Customer Care
Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material
included with standard print versions of this book may not be included in e-books or in print-on-demand.
If this book refers to media such as a CD or DVD that is not included in the version you purchased, you
may download this material at http://booksupport.wiley.com. For more information about Wiley
products, visit www.wiley.com.
Library of Congress Control Number: 2013936244
ISBN 978-1-118-43166-5 (pbk); ISBN 978-1-118-46209-6 (ebk);
ISBN 978-1-118-61188-3 (ebk); ISBN 978-1-118-49418-9 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
About the Author
John Mueller is a freelance author and technical editor. He has writing in his
blood, having produced 91 books and over 300 articles to date. The topics
range from networking to artificial intelligence and from database man-
agement to heads-down programming. Some of his current books include
Windows command-line references, books on VBA and Visio, several books
on C#, and an IronPython programmer’s guide. His technical editing skills
have helped more than 63 authors refine the content of their manuscripts.
John has provided technical editing services to both Data Based Advisor
and Coast Compute magazines. He’s also contributed articles to magazines
like such as Software Quality Connection, DevSource, InformIT, SQL Server
Professional, Visual C++ Developer, Hard Core Visual Basic, asp.netPRO,
Software Test and Performance, and Visual Basic Developer. Be sure to read
John’s blog at http://blog.johnmuellerbooks.com.

When John isn’t working at the computer, you can find him outside in the
garden, cutting wood, or generally enjoying nature. John also likes making
wine and knitting. When not occupied with anything else, he makes glycerin
soap and candles, which comes in handy for gift baskets. You can reach John
on the Internet at [email protected]. John is also setting up a
website at http://www.johnmuellerbooks.com. Feel free to take a look
and make suggestions on how he can improve it.
Dedication
Dedicated to people who have given me hope and who have helped me
realize new potential as an author; on the occasion of their 50th anniversary,
Bill and Karen Bridges.

Author’s Acknowledgments
Thanks to my wife, Rebecca, for working with me to get this book completed.
I really don’t know what I would have done without her help in researching
and compiling some of the information that appears in this book. She also did
a fine job of proofreading my rough draft. Rebecca keeps the house running
while I’m buried in work.

Russ Mullen deserves thanks for his technical edit of this book. He greatly
added to the accuracy and depth of the material you see here. Russ is always
providing me with great URLs for new products and ideas. However, it’s the
testing Russ does that helps most. He’s the sanity check for my work. Russ
also has different computer equipment than mine, so he’s able to point out
flaws that I might not otherwise notice.

Matt Wagner, my agent, deserves credit for helping me get the contract in
the first place and taking care of all the details that most authors don’t really
consider. I always appreciate his assistance. It’s good to know that someone
wants to help.

A number of people read all or part of this book to help me refine the
approach, test the coding examples, and generally provide input that all
readers wish they could have. These unpaid volunteers helped in ways too
numerous to mention here. I especially appreciate the efforts of Eva Beattie,
Glenn Russell, Osvaldo Téllez Almirall, and Gerald Wilson, Jr., who provided
general input, read the entire book, and selflessly devoted themselves to this
project.

Finally, I would like to thank Kim Darosett, Katie Feltman, Virginia Sanders,
Katie Crocker, and the rest of the editorial and production staff at Wiley for
their assistance in bringing this book to print. It’s always nice to work with
such a great group of professionals.
Publisher’s Acknowledgments
We’re proud of this book; please send us your comments at http://dummies.custhelp.com.
For other comments, please contact our Customer Care Department within the U.S. at 877-762-2974,
outside the U.S. at 317-572-3993, or fax 317-572-4002.
Some of the people who helped bring this book to market include the following:
Acquisitions and Editorial Composition Services
Senior Project Editor: Kim Darosett Project Coordinator: Katherine Crocker
Acquisitions Editor: Constance Santisteban Layout and Graphics: Amy Hassos,
Copy Editor: Virginia Sanders Joyce Haughey

Technical Editor: Russ Mullen Proofreaders: Jessica Kramer, Lisa Stiers

Editorial Manager: Leah Michael Indexer: Ty Koontz

Editorial Assistant: Annie Sullivan


Senior Editorial Assistant: Cherie Case
Cover Photo: © kertlis/iStockphoto

Publishing and Editorial for Technology Dummies


Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Acquisitions Director
Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Kathleen Nebenhaus, Vice President and Executive Publisher
Composition Services
Debbie Stailey, Director of Composition Services
Table of Contents
Introduction.................................................................. 1
About This Book............................................................................................... 1
What You Don’t Have to Read......................................................................... 2
Foolish Assumptions........................................................................................ 2
Conventions Used in This Book...................................................................... 3
How This Book Is Organized........................................................................... 3
Part I: Understanding the Basics of JavaScript................................... 3
Part II: Speaking the JavaScript Language........................................... 4
Part III: Meeting JavaScript’s Control Structures................................ 4
Part IV: Interacting with Users and HTML........................................... 4
Part V: Extending JavaScript Further................................................... 5
Part VI: The Part of Tens........................................................................ 5
The companion Website........................................................................ 5
Icons Used in This Book.................................................................................. 6
Where to Go from Here.................................................................................... 6

Part I: Understanding the Basics of JavaScript................ 9


Chapter 1: HTML, Say Hello to JavaScript . . . . . . . . . . . . . . . . . . . . . . . 11
Introducing JavaScript................................................................................... 12
Java and JavaScript aren’t long-lost relatives................................... 13
Recognizing the benefits of JavaScript.............................................. 13
Seeing How JavaScript Fits into an HTML Document................................ 16
Starting an HTML5 document............................................................. 16
Understanding the alert( ) function.................................................... 17
Using the <script> tag........................................................................... 18
Placing the code in the page heading................................................ 19
Relying on external files....................................................................... 20

Chapter 2: Assessing Tools of the Trade . . . . . . . . . . . . . . . . . . . . . . . . . 23


Researching Browsers and Their Debugging Tools................................... 24
Catching up with Firefox...................................................................... 25
Meeting Google Chrome....................................................................... 29
Checking out native browsers: Internet Explorer or Safari............. 33
Checking browser and version........................................................... 34
viii HTML5 Programming with JavaScript For Dummies

Discovering Programs to Write JavaScript................................................. 36


Using a text editor................................................................................ 37
Using a dedicated editor...................................................................... 38
Hosting Your Site............................................................................................ 41
Quickly looking at Web hosting.......................................................... 41
Using JavaScript from your computer............................................... 42
Testing your installation...................................................................... 46

Chapter 3: Integrating HTML5 and JavaScript . . . . . . . . . . . . . . . . . . . . 47


Creating Simple Output................................................................................. 48
Writing to an HTML element............................................................... 48
Creating direct document output....................................................... 50
Avoiding potential problems with output......................................... 51
Working with JavaScript Statements........................................................... 52
Understanding the dot syntax............................................................. 52
Adding multiple statements to a single script.................................. 53
Defining basic code blocks.................................................................. 55
Understanding case sensitivity........................................................... 55
Using white space effectively.............................................................. 55
Using the line continuation character................................................ 56
Writing Comments in JavaScript.................................................................. 57
Creating single-line comments............................................................ 58
Creating multi-line comments............................................................. 59
Preventing code execution by using comments............................... 60
Alerting Visitors That JavaScript Has Something to Say........................... 60
Using the <noscript> tag...................................................................... 60
Using styles............................................................................................ 61

Part II: Speaking the JavaScript Language.................... 63


Chapter 4: Embracing JavaScript Variables . . . . . . . . . . . . . . . . . . . . . 65
Understanding Simple Variables.................................................................. 66
Seeing variables as storage bins......................................................... 66
Declaring variables............................................................................... 67
Discovering variable types.................................................................. 68
Understanding undefined and null variables.................................... 70
Working with Booleans.................................................................................. 71
Working with Numbers.................................................................................. 72
Understanding the operators.............................................................. 73
Doing simple math................................................................................ 78
Changing number formats................................................................... 80
Working with Text.......................................................................................... 83
Concatenating text................................................................................ 83
Changing word and letter formats...................................................... 83
Table of Contents ix
Working with Arrays...................................................................................... 85
Creating an array.................................................................................. 85
Accessing array members................................................................... 86

Chapter 5: Working with Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89


Defining Objects.............................................................................................. 90
Starting with the Object object........................................................... 90
Understanding properties................................................................... 92
Understanding methods...................................................................... 92
Understanding events.......................................................................... 92
Using and Creating Objects........................................................................... 93
Using JavaScript objects...................................................................... 93
Building custom objects...................................................................... 98
Working with Object Literals...................................................................... 100
Creating the name/value pairs.......................................................... 100
Adding new name/value pairs........................................................... 102
Naming Variables and Objects Properly................................................... 102

Chapter 6: Getting to Know the Standard JavaScript Objects . . . . . 103


Defining the Basic JavaScript Objects....................................................... 104
Understanding Object........................................................................ 104
Understanding Number...................................................................... 106
Understanding String......................................................................... 107
Understanding Date............................................................................ 110
Understanding RegExp....................................................................... 114
Introducing the String Object..................................................................... 118
Manipulating and searching strings................................................. 118
Working with regular expressions.................................................... 119
Working with the Date Object..................................................................... 121
Getting today’s date right.................................................................. 121
Calculating differences in dates........................................................ 123

Part III: Meeting JavaScript’s Control Structures......... 125


Chapter 7: Using Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Using the Built-In Functions........................................................................ 127
Working with the Math Object.................................................................... 130
Building Custom Functions......................................................................... 132
Reducing work using functions......................................................... 132
Passing parameters to functions...................................................... 133
Creating functions with a return value............................................ 134
Creating functions with optional and required arguments........... 135
Understanding variable scope.......................................................... 136
Working with Private Properties and Methods........................................ 137
x HTML5 Programming with JavaScript For Dummies

Chapter 8: Making Choices in JavaScript . . . . . . . . . . . . . . . . . . . . . . 141


Understanding the Reasons for Applications to Make Decisions.......... 142
Deciding When to Use the if Statement..................................................... 143
Creating a simple if statement.......................................................... 143
Deciding what else to do.................................................................... 144
Nesting if statements.......................................................................... 144
Switching Between Choices........................................................................ 146
Creating a basic switch...................................................................... 147
Using the default option..................................................................... 148

Chapter 9: Making the Rounds with Loops . . . . . . . . . . . . . . . . . . . . . . 151


Discovering Loops........................................................................................ 152
Learning why loops are useful.......................................................... 152
Running from the dangers of loops.................................................. 153
Creating for Loops........................................................................................ 153
Making your first for loop.................................................................. 154
Using the break statement................................................................. 155
Using the continue statement........................................................... 157
Creating while Loops................................................................................... 160
Using the basic while loop................................................................. 161
Using the do...while loop................................................................... 162
Examining Objects Using for/in.................................................................. 163
Nesting Loops............................................................................................... 165

Chapter 10: Performing Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . 167


Understanding Errors.................................................................................. 168
Defining an error source.................................................................... 168
Defining the error types..................................................................... 170
Catching Errors............................................................................................. 171
Using the try...catch block................................................................. 172
Understanding the Error object........................................................ 173
Throwing Errors........................................................................................... 174

Part IV: Interacting with Users and HTML................... 177


Chapter 11: Understanding the Document Object Model . . . . . . . . . 179
Introducing the Document Object Model (DOM)..................................... 180
Accessing Individual HTML Elements........................................................ 183
Modifying the output stream............................................................. 183
Affecting HTML content..................................................................... 186
Changing attributes............................................................................ 186
Considering Events....................................................................................... 188
Working with Styles...................................................................................... 191
Table of Contents xi
Working with Nodes..................................................................................... 192
Creating new elements....................................................................... 192
Removing existing elements.............................................................. 194

Chapter 12: Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195


Introducing Events....................................................................................... 196
Performing basic event tasks............................................................ 196
Working with attributes..................................................................... 200
Clicking to Create an Event......................................................................... 202
Understanding the objects at your disposal................................... 202
Passing parameters to the event handler function........................ 208
Pressing a Key............................................................................................... 210
Creating Custom Events.............................................................................. 212
Working with the CustomEvent object............................................ 212
Creating the custom event code....................................................... 212

Chapter 13: Connecting with Style: JavaScript and CSS . . . . . . . . . . 215


Changing HTML Elements........................................................................... 216
Working with HTML tags................................................................... 216
Working with heading styles............................................................. 218
Working with IDs................................................................................. 219
Building Dynamic HTML Elements............................................................. 219
Animating and Positioning HTML Elements.............................................. 221
Creating JavaScript-Based Menus.............................................................. 221
Designing the HTML........................................................................... 222
Defining the styles.............................................................................. 223
Creating the JavaScript functions..................................................... 224

Chapter 14: Enhancing HTML5 Forms with JavaScript . . . . . . . . . . . 227


Revisiting the HTML5 Form Features......................................................... 228
Working with the new elements........................................................ 228
Working with the new controls......................................................... 230
Understanding the new attributes.................................................... 233
Accessing Form Elements............................................................................ 235
Validating Forms........................................................................................... 237

Chapter 15: Interacting with Windows . . . . . . . . . . . . . . . . . . . . . . . . . 241


Working with Windows................................................................................ 242
Determining window characteristics............................................... 242
Changing window attributes............................................................. 243
Accessing the Screen................................................................................... 244
Finding a Location........................................................................................ 245
Determining the current location..................................................... 245
Changing the location........................................................................ 246
Searching History......................................................................................... 247
xii HTML5 Programming with JavaScript For Dummies

Working with Navigator............................................................................... 247


Creating a Pop-Up......................................................................................... 249
Controlling line breaks....................................................................... 249
Creating a modal dialog box.............................................................. 250
Using Cookies................................................................................................ 253
Setting a cookie................................................................................... 254
Getting a cookie.................................................................................. 254
Checking a cookie............................................................................... 256

Part V: Extending JavaScript Further........................... 257


Chapter 16: Working with XML in JavaScript . . . . . . . . . . . . . . . . . . . 259
Introducing XML........................................................................................... 260
Gaining an overview of XML.............................................................. 260
Understanding elements.................................................................... 261
Understanding attributes................................................................... 263
Working through a basic file............................................................. 264
Displaying XML Using XSLT........................................................................ 265
Validating XML.............................................................................................. 267
Understanding the concept of well-formed..................................... 268
Discovering XSD.................................................................................. 268
Loading XML with JavaScript...................................................................... 269

Chapter 17: Cleaning Up the Web with AJAX . . . . . . . . . . . . . . . . . . . 271


Introducing AJAX.......................................................................................... 271
Learning the benefits of AJAX........................................................... 272
Understanding how AJAX works....................................................... 272
Deciphering the XMLHttpRequest object........................................ 273
Performing AJAX Tasks Using JavaScript.................................................. 276
Making AJAX Easier with jQuery................................................................ 278

Chapter 18: Making JavaScript Easier with jQuery . . . . . . . . . . . . . . 279


Getting to Know the jQuery Library........................................................... 280
Loading jQuery from Google CDN.............................................................. 282
Doing Things Easier with jQuery................................................................ 284
Gathering elements with selectors................................................... 284
Working with programmatically generated elements.................... 286
Revisiting arrays with jQuery............................................................ 288
Interrogating an array........................................................................ 289
Handling Events with jQuery...................................................................... 290
Understanding the event functionality............................................ 290
Working with events........................................................................... 296
Table of Contents xiii
Chapter 19: Using jQuery to Handle AJAX . . . . . . . . . . . . . . . . . . . . . . 299
Understanding the AJAX Object in jQuery................................................ 300
Considering the global AJAX event handlers.................................. 300
Working with the helper functions................................................... 301
Understanding the low-level interface............................................. 302
Using shorthand methods................................................................. 303
Discovering Server-Side Programming...................................................... 304
Adding PHP support to your Apache server................................... 304
Testing your PHP configuration........................................................ 306
Creating the PHP script...................................................................... 306
Retrieving Results from AJAX Calls............................................................ 308
Working with standard output.......................................................... 308
Investigating the benefits of JSON.................................................... 310

Chapter 20: Animating the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313


Getting to Know jQuery UI........................................................................... 314
Considering interactions................................................................... 314
Understanding the widgets................................................................ 322
Defining the effects............................................................................. 333
Canvasing Your Web Page........................................................................... 340
Understanding what the canvas does.............................................. 340
Creating a simple Google API application....................................... 341

Part VI: The Part of Tens............................................ 345


Chapter 21: Ten Incredible HTML5 and JavaScript Examples . . . . . 347
Creating an XML-Based Menu..................................................................... 348
Creating an XML-Based Tabbed Interface................................................. 352
Displaying a Slideshow................................................................................ 355
Employing Custom Spinners....................................................................... 358
Working with Timepickers.......................................................................... 361
Creating a Standardized Look with CSS..................................................... 362
Displaying a Category and Detail Data View............................................. 363
Selecting Data Using a Calendar................................................................. 367
Developing a User-Configurable Interface................................................. 370
Devising a Simple Survey Form................................................................... 371

Chapter 22: Ten Thoughts About the Future of Web Development . . . 375
Automating More Tasks............................................................................... 375
Developing Applications That Run Anywhere.......................................... 376
Using Standards for Every Application...................................................... 376
Creating a Desktop Environment with a Browser.................................... 377
xiv HTML5 Programming with JavaScript For Dummies

Using a Centralized Data Store................................................................... 377


Creating Mobile-friendly Applications....................................................... 378
Developing Accessible Applications.......................................................... 378
Building New Application Types................................................................ 379
Thinking More About Users........................................................................ 379
Expecting Unexpected Connections.......................................................... 380

Index........................................................................ 381
Introduction
H ave you people-watched lately? If not, you really should. People-
watching is both fun and educational. At one time, you wouldn’t see
people using computers wherever they went because computers were large,
cumbersome devices that no one wanted to take out of the office. Today, you
have a hard time finding people who aren’t using a computing device of some
sort to perform some task. Developers have an incredible opportunity today
to affect people in every walk of life and in any situation imaginable because
people carry their computing devices with them far and wide to hold every
bit of information they find valuable.

The tools that developers use to create applications must change to reflect
this new reality, and HTML5 and JavaScript are the most appropriate tools
to accomplish the goals developers have today. You can use the combina-
tion of HTML5 and JavaScript to create applications that run on any device
using just about any new browser. HTML5 Programming with JavaScript For
Dummies is your gateway to an incredible new future of development where
you aren’t limited to a specific platform or some vendor’s concept of what
tools you should use to create applications. This book helps you gain the
skills required to create the new sorts of applications that developers have
always wanted to write.

About This Book


HTML5 Programming with JavaScript For Dummies is about possibilities. It
focuses on getting started writing code quickly and efficiently. You see lots
of coding examples, all of which demonstrate principles you need for writing
applications that people want to use today. The latter part of the book actu-
ally shows some application programming techniques you can use directly
in production applications. The method used to accomplish this goal is the
same method that all smart developers use today — borrowing code from
someone else. This book emphasizes the use of templates and libraries to
make your coding experience fun and simple rather than cumbersome and
boring, as it might have been in the past.

Don’t worry about becoming immediately lost in detail. Like every For
Dummies book, this one takes things slowly, and all the examples are
explained thoroughly so that you know precisely how they work. You’ll find
that you advance quickly because this book takes advantage of the best
2 HTML5 Programming with JavaScript For Dummies

possible techniques that knowledgeable developers use to make their lives


simple. Working with libraries such as jQuery greatly decreases the work you
have to do while simultaneously making the application you create look pro-
fessional, and best of all, work everywhere on every device.

Of course, every developer needs to be aware of at least the basics, and the
introductory chapters of the book do just that — they tell you how things
work under the cover. Sometimes you need this information in order to make
the best use possible of all those third-party offerings. However, as the text
often states, there’s no need to reinvent the wheel. Your JavaScript applica-
tions will look professional because you’re using professionally written code
to develop them. This book shows you how to create some truly impressive
results in an incredibly short timeframe.

What You Don’t Have to Read


Most of the chapters contain some advanced material that will interest only
some readers. When you see one of these specialized topics, feel free to
skip it. Most of this advanced material appears in sidebars. The sidebar title
always indicates the nature of the advanced material.

You can also skip any material marked with a Technical Stuff icon. This mate-
rial is helpful, but you don’t have to know it to work with HTML or JavaScript.
I include this material because I find it helpful in my programming efforts and
believe that you will, too.

Foolish Assumptions
You might find it difficult to believe that I’ve assumed anything about you —
after all, I haven’t even met you yet! Although most assumptions are indeed
foolish, I made these assumptions to provide a starting point for the book.

It’s important that you’re familiar with the platform and browser you want
to use because the book doesn’t provide any handholding in this regard. To
focus on HTML5 and JavaScript as fully as possible, the book covers brows-
ers marginally and platform requirements not at all. You really do need to
know how to install applications, use the browser, and generally work with
your chosen platform before you begin working with this book.

Knowing a little about HTML is helpful but not essential. Any experience you
have with programming will be helpful as well. The book doesn’t assume you
have any knowledge of JavaScript.
Introduction 3
Conventions Used in This Book
This book uses special typeface to emphasize some information. For exam-
ple, entries that you need to type appear in bold. All code, Website URLs, and
onscreen messages appear in monofont type. When I define a new word,
you see that word in italics.

Because you use multiple applications when you’re working with JavaScript,
I always point out when to move from one application to the next. However,
the testers for this book tried out the code with the Internet Explorer, Firefox,
and Chrome browsers on the Macintosh, Linux, and Windows platforms. One
tester also checked at least some of the code using a Windows 8 phone. In
most cases, you shouldn’t experience any problem working with your appli-
cation unless specifically noted in the application description. Please let me
know at [email protected] if you ever experience a problem
with one of the examples.

How This Book Is Organized


This book contains several parts. Each part demonstrates a particular
JavaScript concept. In each chapter, I discuss a particular topic and include
example programs that you can use to discover more about JavaScript on
your own. It isn’t necessary to read the book cover-to-cover — you can
peruse the topics you find most interesting as you would with any refer-
ence book. However, you’ll get more from the book if you do read it cover-
to-cover. You can find the source code for this book on the Dummies.com
Website at http://www.dummies.com/go/html5programmingwith
javascript.

Part I: Understanding the


Basics of JavaScript
This part of the book helps you gain a perspective of what the language can
do for you as a developer and then shows you some simple examples of
how the language works. Chapter 1 exposes you to JavaScript by presenting
simple examples — you aren’t expected to fully understand how they work,
but you do gain an understanding of what JavaScript is like and how it could
potentially help you create amazing browser-based applications. Chapter 2
spends time exploring some common tools you should consider using when
writing your JavaScript applications. Chapter 3 begins exploring how HTML5
and JavaScript work together to create a useful programming environment.
4 HTML5 Programming with JavaScript For Dummies

Part II: Speaking the JavaScript Language


Before you can do anything with JavaScript, you need to know how to speak
the language. Chapters 4, 5, and 6 introduce you to the essential elements of
the JavaScript language in the form of variables and objects. Everything in
JavaScript is an object. Before you can do anything else, you need to under-
stand these objects and discover how to use them.

Part III: Meeting JavaScript’s


Control Structures
Complex applications rely on control structures to organize tasks, optionally
perform them, and perform them repetitively. Chapter 7 focuses on func-
tions, which are the JavaScript method of organizing tasks in easily under-
stood and reusable pieces. Chapter 8 tells you how to make decisions using
JavaScript code. Finally, Chapter 9 discusses techniques for performing tasks
repetitively. Taken together, these three chapters help you create complete
and useful JavaScript applications.

This part of the book also discusses errors. Errors can happen in every
application, even when that application has no errors in it. A user can
enter incorrect data or an environmental factor can cause various sorts of
data degradation and loss. Many errors are completely out of your hands.
However, recovering from these errors is completely within your grasp,
which is the topic of Chapter 10.

Part IV: Interacting with Users and HTML


This part of the book focuses on user interactions. The basis of interaction
in JavaScript is the Document Object Model (DOM), which is the focus of
Chapter 11. To react to user actions and external activity, your application
must handle events. Chapter 12 describes all sorts of events and how you can
handle them within your application.

Creating a good presentation also helps you motivate users to interact with
your application. Chapters 13, 14, and 15 discuss various kinds of presenta-
tion techniques you use to create successful applications with JavaScript.
Discovering Diverse Content Through
Random Scribd Documents
all fear of everything terrible, not only of death, but also poverty and
disease, and ignominy, and things akin to these; being unconquered
by pleasure, and lord over irrational desires. For he well knows what
is and what is not to be done; being perfectly aware what things are
really to be dreaded, and what not. Whence he bears intelligently
what the Word intimates to him to be requisite and necessary;
intelligently discriminating what is really safe (that is, good), from
what appears so; and things to be dreaded from what seem so, such
as death, disease, and poverty; which are rather so in opinion than in
truth.
This is the really good man, who is without passions; having,
through the habit or disposition of a soul endued with virtue,
transcended the whole life of passion. He has everything dependent
on himself for the attainment of the end. For those accidents which
are called terrible are not formidable to the good man, because they
are not evil. And those which are really to be dreaded are foreign to
the gnostic Christian, being diametrically opposed to what is good,
because evil; and it is impossible for contraries to meet in the same
person at the same time. He, then, who faultlessly acts the drama of
life which God has given him to play, knows both what is to be done
and what is to be endured.
Is it not then from ignorance of what is and what is not to be
dreaded that cowardice arises? Consequently the only man of
courage is the Gnostic, who knows both present and future good
things; along with these, knowing, as I have said, also the things
which are in reality not to be dreaded. Because, knowing vice alone
to be hateful, and destructive of what contributes to knowledge,
protected by the armour of the Lord, he makes war against it.
For if anything is caused through folly, and the operation or rather
co-operation of the devil, this thing is not straightway the devil or
folly. For no action is wisdom. For wisdom is a habit. And no action is
a habit. The action, then, that arises from ignorance, is not already
ignorance, but an evil through ignorance, but not ignorance. For
neither perturbations of mind nor sins are vices, though proceeding
from vice.
No one, then, who is irrationally brave is a Gnostic; since one
might call children brave, who, through ignorance of what is to be
dreaded, undergo things that are frightful. So they touch fire even.
And the wild beasts that rush close on the points of spears, having a
brute courage, might be called valiant. And such people might
perhaps call jugglers valiant, who tumble on swords with a certain
dexterity, practising a mischievous art for sorry gain. But he who is
truly brave, with the peril arising from the bad feeling of the multitude
before his eyes, courageously awaits whatever comes. In this way
he is distinguished from others that are called martyrs, inasmuch as
some furnish occasions for themselves, and rush into the heart of
dangers, I know not how (for it is right to use mild language); while
they, in accordance with right reason, protect themselves; then, on
God really calling them, promptly surrender themselves, and confirm
the call, from being conscious of no precipitancy, and present the
man to be tested in the exercise of true rational fortitude. Neither,
then, enduring lesser dangers from fear of greater, like other people,
nor dreading censure at the hands of their equals, and those of like
sentiments, do they continue in the confession of their calling; but
from love to God they willingly obey the call, with no other aim in
view than pleasing God, and not for the sake of the reward of their
toils.
For some suffer from love of glory, and others from fear of some
other sharper punishment, and others for the sake of pleasures and
delights after death, being children in faith; blessed indeed, but not
yet become men in love to God, as the Gnostic is. For there are, as
in the gymnastic contests, so also in the Church, crowns for men and
for children. But love is to be chosen for itself, and for nothing else.
Therefore in the Gnostic, along with knowledge, the perfection of
fortitude is developed from the discipline of life, he having always
studied to acquire mastery over the passions.
Accordingly, love makes its own athlete fearless and dauntless,
and confident in the Lord, anointing and training him; as
righteousness secures for him truthfulness in his whole life. For it
was a compendium of righteousness to say, “Let your yea be yea;
and your nay, nay.”
And the same holds with self-control. For it is neither for love of
honour, as the athletes for the sake of crowns and fame; nor, on the
other hand, for love of money, as some pretend to exercise self-
control, pursuing what is good with terrible suffering. Nor is it from
love of the body for the sake of health. Nor any more is any man who
is temperate from rusticity, who has not tasted pleasures, truly a man
of self-control. Certainly those who have led a laborious life, on
tasting pleasures, forthwith break down the inflexibility of temperance
into pleasures. Such are they who are restrained by law and fear.
For on finding a favourable opportunity they defraud the law, by
giving what is good the slip. But self-control, desirable for its own
sake, perfected through knowledge, abiding ever, makes the man
lord and master of himself; so that the Gnostic is temperate and
passionless, incapable of being dissolved by pleasures and pains, as
they say adamant is by fire.
The cause of these, then, is love, of all science the most sacred
and most sovereign.
For by the service of what is best and most exalted, which is
characterized by unity, it renders the Gnostic at once friend and son,
having in truth grown “a perfect man, up to the measure of full
stature.”[1257]
Further, agreement in the same thing is consent. But what is the
same is one. And friendship is consummated in likeness; the
community lying in oneness. The Gnostic, consequently, in virtue of
being a lover of the one true God, is the really perfect man and friend
of God, and is placed in the rank of son. For these are names of
nobility and knowledge, and perfection in the contemplation of God;
which crowning step of advancement the gnostic soul receives,
when it has become quite pure, reckoned worthy to behold
everlastingly God Almighty, “face,” it is said, “to face.” For having
become wholly spiritual, and having in the spiritual Church gone to
what is of kindred nature, it abides in the rest of God.
CHAPTER XII.
THE TRUE GNOSTIC IS BENEFICENT, CONTINENT, AND DESPISES
WORLDLY THINGS.

Let these things, then, be so.


And such being the attitude of the Gnostic towards the body and
the soul—towards his neighbours, whether it be a domestic, or a
lawful enemy, or whosoever—he is found equal and like. For he
does not “despise his brother,” who, according to the divine law, is of
the same father and mother. Certainly he relieves the afflicted,
helping him with consolations, encouragements, and the necessaries
of life; giving to all that need, though not similarly, but justly,
according to desert; furthermore, to him who persecutes and hates,
even if he need it; caring little for those who say to him that he has
given out of fear, if it is not out of fear that he does so, but to give
help. For how much more are those, who towards their enemies are
devoid of love of money, and are haters of evil, animated with love to
those who belong to them?
Such an one from this proceeds to the accurate knowledge of
whom he ought chiefly to give to, and how much, and when, and
how.
And who could with any reason become the enemy of a man who
gives no cause for enmity in any way? And is it not just as in the
case of God? We say that God is the adversary of no one, and the
enemy of no one (for He is the Creator of all, and nothing that exists
is what He wills it not to be; but we assert that the disobedient, and
those who walk not according to His commandments, are enemies to
Him, as being those who are hostile to His covenant). We shall find
the very same to be the case with the Gnostic, for he can never in
any way become an enemy to any one; but those may be regarded
enemies to him who turn to the contrary path.
In particular, the habit of liberality which prevails among us is
called “righteousness;” but the power of discriminating according to
desert, as to greater and less, with reference to those who are
proper subjects of it, is a form of the very highest righteousness.
There are things practised in a vulgar style by some people, such
as control over pleasures. For as, among the heathen, there are
those who, from the impossibility of obtaining what one sees,[1258]
and from fear of men, and also for the sake of greater pleasures,
abstain from the delights that are before them; so also, in the case of
faith, some practise self-restraint, either out of regard to the promise
or from fear of God. Well, such self-restraint is the basis of
knowledge, and an approach to something better, and an effort after
perfection. For “the fear of the Lord,” it is said, “is the beginning of
wisdom.”[1259] But the perfect man, out of love, “beareth all things,
endureth all things,”[1260] “as not pleasing man, but God.”[1261]
Although praise follows him as a consequence, it is not for his own
advantage, but for the imitation and benefit of those who praise him.
According to another view, it is not he who merely controls his
passions that is called a continent man, but he who has also
achieved the mastery over good things, and has acquired surely the
great accomplishments of science, from which he produces as fruits
the activities of virtue. Thus the Gnostic is never, on the occurrence
of an emergency, dislodged from the habit peculiar to him. For the
scientific possession of what is good is firm and unchangeable,
being the knowledge of things divine and human. Knowledge, then,
never becomes ignorance; nor does good change into evil.
Wherefore also he eats, and drinks, and marries, not as principal
ends of existence, but as necessary. I name marriage even, if the
Word prescribe, and as is suitable. For having become perfect, he
has the apostles for examples; and one is not really shown to be a
man in the choice of single life; but he surpasses men, who,
disciplined by marriage, procreation of children, and care for the
house, without pleasure or pain, in his solicitude for the house has
been inseparable from God’s love, and withstood all temptation
arising through children, and wife, and domestics, and possessions.
But he that has no family is in a great degree free of temptation.
Caring, then, for himself alone, he is surpassed by him who is
inferior, as far as his own personal salvation is concerned, but who is
superior in the conduct of life, preserving certainly, in his care for the
truth, a minute image.
But we must as much as possible subject the soul to varied
preparatory exercise, that it may become susceptible to the
reception of knowledge. Do you not see how wax is softened and
copper purified, in order to receive the stamp applied to it? Just as
death is the separation of the soul from the body, so is knowledge as
it were the rational death urging the spirit away, and separating it
from the passions, and leading it on to the life of well-doing, that it
may then say with confidence to God, “I live as Thou wishest.” For
he who makes it his purpose to please men cannot please God,
since the multitude choose not what is profitable, but what is
pleasant. But in pleasing God, one as a consequence gets the
favour of the good among men. How, then, can what relates to meat,
and drink, and amorous pleasure, be agreeable to such an one?
since he views with suspicion even a word that produces pleasure,
and a pleasant movement and act of the mind. “For no one can
serve two masters, God and Mammon,”[1262] it is said; meaning not
simply money, but the resources arising from money bestowed on
various pleasures. In reality, it is not possible for him who
magnanimously and truly knows God, to serve antagonistic
pleasures.
There is one alone, then, who from the beginning was free of
concupiscence—the philanthropic Lord, who for us became man.
And whosoever endeavour to be assimilated to the impress given by
Him, strive, from exercise, to become free of concupiscence. For he
who has exercised concupiscence and then restrained himself, is
like a widow who becomes again a virgin by continence. Such is the
reward of knowledge, rendered to the Saviour and Teacher, which
He Himself asked for,—abstinence from what is evil, activity in doing
good, by which salvation is acquired.
As, then, those who have learned the arts procure their living by
what they have been taught, so also is the Gnostic saved, procuring
life by what he knows. For he who has not formed the wish to
extirpate the passion of the soul, kills himself. But, as seems,
ignorance is the starvation of the soul, and knowledge its
sustenance.
Such are the gnostic souls, which the Gospel likened to the
consecrated virgins who wait for the Lord. For they are virgins, in
respect of their abstaining from what is evil. And in respect of their
waiting out of love for the Lord, and kindling their light for the
contemplation of things, they are wise souls, saying, “Lord, for long
we have desired to receive Thee; we have lived according to what
Thou hast enjoined, transgressing none of Thy commandments.
Wherefore also we claim the promises. And we pray for what is
beneficial, since it is not requisite to ask of Thee what is most
excellent. And we shall take everything for good; even though the
exercises that meet us, which Thine arrangement brings to us for the
discipline of our stedfastness, appear to be evil.”
The Gnostic, then, from his exceeding holiness, is better prepared
to fail when he asks, than to get when he does not ask.
His whole life is prayer and converse with God. And if he be pure
from sins, he will by all means obtain what he wishes. For God says
to the righteous man, “Ask, and I will give thee; think, and I will do.” If
beneficial, he will receive it at once; and if injurious, he will never ask
it, and therefore he will not receive it. So it shall be as he wishes.
But if one say to us, that some sinners even obtain according to
their requests, [we should say] that this rarely takes place, by reason
of the righteous goodness of God. And it is granted to those who are
capable of doing others good. Whence the gift is not made for the
sake of him that asked it; but the divine dispensation, foreseeing that
one would be saved by his means, renders the boon again
righteous. And to those who are worthy, things which are really good
are given, even without their asking.
Whenever, then, one is righteous, not from necessity or out of fear
or hope, but from free choice, this is called the royal road, which the
royal race travel. But the byways are slippery and precipitous. If,
then, one take away fear and honour, I do not know if the illustrious
among the philosophers, who use such freedom of speech, will any
longer endure afflictions.
Now lusts and other sins are called “briars and thorns.”
Accordingly the Gnostic labours in the Lord’s vineyard, planting,
pruning, watering; being the divine husbandman of what is planted in
faith. Those, then, who have not done evil, think it right to receive the
wages of ease. But he who has done good out of free choice,
demands the recompense as a good workman. He certainly shall
receive double wages—both for what he has not done, and for what
good he has done.
Such a Gnostic is tempted by no one except with God’s
permission, and that for the benefit of those who are with him; and
he strengthens them for faith, encouraging them by manly
endurance. And assuredly it was for this end, for the establishment
and confirmation of the churches, that the blessed apostles were
brought into trial and to martyrdom.
The Gnostic, then, hearing a voice ringing in his ear, which says,
“Whom I shall strike, do thou pity,” beseeches that those who hate
him may repent. For the punishment of malefactors, to be
consummated in the highways, is for children to witness;[1263] for
there is no possibility of the Gnostic, who has from choice trained
himself to be excellent and good, ever being instructed or delighted
with such spectacles.[1264] And so, having become incapable of
being softened by pleasures, and never falling into sins, he is not
corrected by the examples of other men’s sufferings. And far from
being pleased with earthly pleasures and spectacles is he who has
shown a noble contempt for the prospects held out in this world,
although they are divine.
“Not every one,” therefore, “that says Lord, Lord, shall enter into
the kingdom of God; but he that doeth the will of God.”[1265] Such is
the gnostic labourer, who has the mastery of worldly desires even
while still in the flesh; and who, in regard to things future and still
invisible, which he knows, has a sure persuasion, so that he regards
them as more present than the things within reach. This able
workman rejoices in what he knows, but is cramped on account of
his being involved in the necessities of life; not yet deemed worthy of
the active participation in what he knows. So he uses this life as if it
belonged to another,—so far, that is, as is necessary.
He knows also the enigmas of the fasting of those days—I mean
the Fourth and the Preparation. For the one has its name from
Hermes, and the other from Aphrodite. He fasts in his life, in respect
of covetousness and voluptuousness, from which all the vices grow.
For we have already often above shown the three varieties of
fornication, according to the apostle—love of pleasure, love of
money, idolatry. He fasts, then, according to the Law, abstaining from
bad deeds, and, according to the perfection of the Gospel, from evil
thoughts. Temptations are applied to him, not for his purification, but,
as we have said, for the good of his neighbours, if, making trial of
toils and pains, he has despised and passed them by.
The same holds of pleasure. For it is the highest achievement for
one who has had trial of it, afterwards to abstain. For what great
thing is it, if a man restrains himself in what he knows not? He, in
fulfilment of the precept, according to the Gospel, keeps the Lord’s
day, when he abandons an evil disposition, and assumes that of the
Gnostic, glorifying the Lord’s resurrection in himself. Further also,
when he has received the comprehension of scientific speculation,
he deems that he sees the Lord, directing his eyes towards things
invisible, although he seems to look on what he does not wish to
look on; chastising the faculty of vision, when he perceives himself
pleasurably affected by the application of his eyes; since he wishes
to see and hear that alone which concerns him.
In the act of contemplating the souls of the brethren, he beholds
the beauty of the flesh also, with the soul itself, which has become
habituated to look solely upon that which is good, without carnal
pleasure. And they are really brethren; inasmuch as, by reason of
their elect creation, and their oneness of character, and the nature of
their deeds, they do, and think, and speak the same holy and good
works, in accordance with the sentiments with which the Lord wished
them as elect to be inspired.
For faith shows itself in their making choice of the same things;
and knowledge, in learning and thinking the same things; and hope,
in desiring[1266] the same things.
And if, through the necessity of life, he spend a small portion of
time about his sustenance, he thinks himself defrauded, being
diverted by business. Thus not even in dreams does he look on
aught that is unsuitable to an elect man. For thoroughly[1267] a
stranger and sojourner in the whole of life is every such one, who,
inhabiting the city, despises the things in the city which are admired
by others, and lives in the city as in a desert, so that the place may
not compel him, but his mode of life show him to be just.
This Gnostic, to speak compendiously, makes up for the absence
of the apostles, by the rectitude of his life, the accuracy of his
knowledge, by benefiting his relations, by “removing the mountains”
of his neighbours, and putting away the irregularities of their soul.
Although each of us is his[1268] own vineyard and labourer.
He, too, while doing the most excellent things, wishes to elude the
notice of men, persuading the Lord along with himself that he is
living in accordance with the commandments, preferring these things
from believing them to exist. “For where any one’s mind is, there also
is his treasure.”[1269]
He impoverishes himself, in order that he may never overlook a
brother[1270] who has been brought into affliction, through the
perfection that is in love, especially if he know that he will bear want
himself easier than his brother. He considers, accordingly, the other’s
pain his own grief; and if, by contributing from his own indigence in
order to do good, he suffer any hardship, he does not fret at this, but
augments his beneficence still more. For he possesses in its
sincerity the faith which is exercised in reference to the affairs of life,
and praises the gospel in practice and contemplation. And, in truth,
he wins his praise “not from men, but from God,”[1271] by the
performance of what the Lord has taught.
He, attracted by his own hope, tastes not the good things that are
in the world, entertaining a noble contempt for all things here; pitying
those that are chastised after death, who through punishment
unwillingly make confession; having a clear conscience with
reference to his departure, and being always ready, as “a stranger
and pilgrim,” with regard to the inheritances here; mindful only of
those that are his own, and regarding all things here as not his own;
not only admiring the Lord’s commandments, but, so to speak, being
by knowledge itself partaker of the divine will; a truly chosen intimate
of the Lord and His commands in virtue of being righteous; and
princely and kingly as being a Gnostic; despising all the gold on
earth and under the earth, and dominion from shore to shore of
ocean, so that he may cling to the sole service of the Lord.
Wherefore also, in eating, and drinking, and marrying (if the Word
enjoin), and even in seeing dreams, he does and thinks what is holy.
So is he always pure for prayer. He also prays in the society of
angels, as being already of angelic rank, and he is never out of their
holy keeping; and though he pray alone, he has the choir of the
saints[1272] standing with him.
He recognises a twofold [element in faith], both the activity of him
who believes, and the excellence of that which is believed according
to its worth; since also righteousness is twofold, that which is out of
love, and that from fear. Accordingly it is said, “The fear of the Lord is
pure, remaining for ever and ever.”[1273] For those that from fear turn
to faith and righteousness, remain for ever. Now fear works
abstinence from what is evil; but love exhorts to the doing of good,
by building up to the point of spontaneousness; that one may hear
from the Lord, “I call you no longer servants, but friends,” and may
now with confidence apply himself to prayer.
And the form of his prayer is thanksgiving for the past, for the
present, and for the future as already through faith present. This is
preceded by the reception of knowledge. And he asks to live the
allotted life in the flesh as a Gnostic, as free from the flesh, and to
attain to the best things, and flee from the worse. He asks, too, relief
in those things in which we have sinned, and conversion to the
acknowledgment of them.
He follows, on his departure, Him who calls, as quickly, so to
speak, as He who goes before calls, hasting by reason of a good
conscience to give thanks; and having got there with Christ, shows
himself worthy, through his purity, to possess, by a process of
blending, the power of God communicated by Christ. For he does
not wish to be warm by participation in heat, or luminous by
participation in flame, but to be wholly light.
He knows accurately the declaration, “Unless ye hate father and
mother, and besides your own life, and unless ye bear the sign [of
the cross].”[1274] For he hates the inordinate affections of the flesh,
which possess the powerful spell of pleasure; and entertains a noble
contempt for all that belongs to the creation and nutriment of the
flesh. He also withstands the corporeal[1275] soul, putting a bridle-bit
on the restive irrational spirit: “For the flesh lusteth against the
Spirit.”[1276] And “to bear the sign of [the cross]” is to bear about
death, by taking farewell of all things while still alive; since there is
not equal love in “having sown the flesh,”[1277] and in having formed
the soul for knowledge.
He having acquired the habit of doing good, exercises
beneficence well, quicker than speaking; praying that he may get a
share in the sins of his brethren, in order to confession and
conversion on the part of his kindred; and eager to give a share to
those dearest to him of his own good things. And so these are to
him, friends. Promoting, then, the growth of the seeds deposited in
him, according to the husbandry enjoined by the Lord, he continues
free of sin, and becomes continent, and lives in spirit with those who
are like him, among the choirs of the saints, though still detained on
earth.
He, all day and night, speaking and doing the Lord’s commands,
rejoices exceedingly, not only on rising in the morning and at noon,
but also when walking about, when asleep, when dressing and
undressing; and he teaches his son, if he has a son. He is
inseparable from the commandment and from hope, and is ever
giving thanks to God, like the living creatures figuratively spoken of
by Esaias, and submissive in every trial, he says, “The Lord gave,
and the Lord hath taken away.”[1278] For such also was Job; who
after the spoiling of his effects, along with the health of his body,
resigned all through love to the Lord. For “he was,” it is said, “just,
holy, and kept apart from all wickedness.”[1279] Now the word “holy”
points out all duties toward God, and the entire course of life.
Knowing which, he was a Gnostic. For we must neither cling too
much to such things, even if they are good, seeing they are human,
nor on the other hand detest them, if they are bad; but we must be
above both [good and bad], trampling the latter under foot, and
passing on the former to those who need them. But the Gnostic is
cautious in accommodation, lest he be not perceived, or lest the
accommodation become disposition.
CHAPTER XIII.
DESCRIPTION OF THE GNOSTIC CONTINUED.

He never remembers those who have sinned against him, but


forgives them. Wherefore also he righteously prays, saying, “Forgive
us; for we also forgive.”[1280] For this also is one of the things which
God wishes, to covet nothing, to hate no one. For all men are the
work of one will. And is it not the Saviour, who wishes the Gnostic to
be perfect as “the heavenly Father,”[1281] that is, Himself, who says,
“Come, ye children, hear from me the fear of the Lord?”[1282] He
wishes him no longer to stand in need of help by angels, but to
receive it from Himself, having become worthy, and to have
protection from Himself by obedience.
Such an one demands from the Lord, and does not merely ask.
And in the case of his brethren in want, the Gnostic will not ask
himself for abundance of wealth to bestow, but will pray that the
supply of what they need may be furnished to them. For so the
Gnostic gives his prayer to those who are in need, and by his prayer
they are supplied, without his knowledge, and without vanity.
Penury and disease, and such trials, are often sent for
admonition, for the correction of the past, and for care for the future.
Such an one prays for relief from them, in virtue of possessing the
prerogative of knowledge, not out of vainglory; but from the very fact
of his being a Gnostic, he works beneficence, having become the
instrument of the goodness of God.
They say in the traditions that Matthew the apostle constantly
said, that “if the neighbour of an elect man sin, the elect man has
sinned. For had he conducted himself as the Word prescribes, his
neighbour also would have been filled with such reverence for the
life he led as not to sin.”
What, then, shall we say of the Gnostic himself? “Know ye not,”
says the apostle, “that ye are the temple of God?”[1283] The Gnostic
is consequently divine, and already holy, God-bearing, and God-
borne. Now the Scripture, showing that sinning is foreign to him,
sells those who have fallen away to strangers, saying, “Look not on a
strange woman, to lust,”[1284] plainly pronounces sin foreign and
contrary to the nature of the temple of God. Now the temple is great,
as the Church, and it is small, as the man who preserves the seed of
Abraham. He, therefore, who has God resting in him will not desire
aught else. At once leaving all hindrances, and despising all matter
which distracts him, he cleaves the heaven by knowledge. And
passing through the spiritual Essences, and all rule and authority, he
touches the highest thrones, hasting to that alone for the sake of
which alone he knew.
Mixing, then, “the serpent with the dove,”[1285] he lives at once
perfectly and with a good conscience, mingling faith with hope, in
order to the expectation of the future. For he is conscious of the
boon he has received, having become worthy of obtaining it; and is
translated from slavery to adoption, as the consequence of
knowledge; knowing God, or rather known of Him, for the end, he
puts forth energies corresponding to the worth of grace. For works
follow knowledge, as the shadow the body.
Rightly, then, he is not disturbed by anything which happens; nor
does he suspect those things, which, through divine arrangement,
take place for good. Nor is he ashamed to die, having a good
conscience, and being fit to be seen by the Powers. Cleansed, so to
speak, from all the stains of the soul, he knows right well that it will
be better with him after his departure.
Whence he never prefers pleasure and profit to the divine
arrangement, since he trains himself by the commands, that in all
things he may be well pleasing to the Lord, and praiseworthy in the
sight of the world, since all things depend on the one Sovereign God.
The Son of God, it is said, came to His own, and His own received
Him not. Wherefore also in the use of the things of the world he not
only gives thanks and praises the creation, but also, while using
them as is right, is praised; since the end he has in view terminates
in contemplation by gnostic activity in accordance with the
commandments.
Thence now, by knowledge collecting materials to be the food of
contemplation, having embraced nobly the magnitude of knowledge,
he advances to the holy recompense of translation hence. For he
has heard the Psalm which says: “Encircle Zion, and encompass it,
tell upon its towers.”[1286] For it intimates, I think, those who have
sublimely embraced the Word, so as to become lofty towers, and to
stand firmly in faith and knowledge.
Let these statements concerning the Gnostic, containing the
germs of the matter in as brief terms as possible, be made to the
Greeks. But let it be known that if the [mere] believer do rightly one
or a second of these things, yet he will not do so in all nor with the
highest knowledge, like the Gnostic.
CHAPTER XIV.
DESCRIPTION OF THE GNOSTIC FURNISHED BY AN EXPOSITION OF 1
COR. VI. 1, ETC.

Now, of what I may call the passionlessness which we attribute to


the Gnostic (in which the perfection of the believer, “advancing by
love, comes to a perfect man, to the measure of full stature,”[1287] by
being assimilated to God, and by becoming truly angelic), many
other testimonies from the Scripture occur to me to adduce. But I
think it better, on account of the length of the discourse, that such an
honour should be devolved on those who wish to take pains, and
leave it to them to elaborate the dogmas by the selection of
scriptures.
One passage, accordingly, I shall in the briefest terms advert to,
so as not to leave the topic unexplained.
For in the first Epistle to the Corinthians the divine apostle says:
“Dare any of you, having a matter against the other, go to law before
the unrighteous, and not before the saints? Know ye not that the
saints shall judge the world?”[1288] and so on.
The section being very lengthy, we shall exhibit the meaning of
the apostle’s utterance by employing such of the apostolic
expressions as are most pertinent, and in the briefest language, and
in a sort of cursory way, interpreting the discourse in which he
describes the perfection of the Gnostic. For he does not merely
instance the Gnostic as characterized by suffering wrong rather than
do wrong; but he teaches that he is not mindful of injuries, and does
not allow him even to pray against the man who has done him
wrong. For he knows that the Lord expressly enjoined “to pray for
enemies.”[1289]
To say, then, that the man who has been injured goes to law
before the unrighteous, is nothing else than to say that he shows a
wish to retaliate, and a desire to injure the second in return, which is
also to do wrong likewise himself.
And his saying, that he wishes “some to go to law before the
saints,” points out those who ask by prayer that those who have
done wrong should suffer retaliation for their injustice, and intimates
that the second are better than the former; but they are not yet
obedient,[1290] if they do not, having become entirely free of
resentment, pray even for their enemies.
It is well, then, for them to receive right dispositions from
repentance, which results in faith. For if the truth seems to get
enemies who entertain bad feeling, yet it is not hostile to any one.
“For God makes His sun to shine on the just and on the unjust,”[1291]
and sent the Lord Himself to the just and the unjust. And he that
earnestly strives to be assimilated to God, in the exercise of great
absence of resentment, forgives seventy times seven times, as it
were all his life through, and in all his course in this world (that being
indicated by the enumeration of sevens) shows clemency to each
and any one; if any during the whole time of his life in the flesh do
the Gnostic wrong. For he not only deems it right that the good man
should resign his property alone to others, being of the number of
those who have done him wrong; but also wishes that the righteous
man should ask of those judges forgiveness for the offences of those
who have done him wrong. And with reason, if indeed it is only in
that which is external and concerns the body, though it go to the
extent of death even, that those who attempt to wrong him take
advantage of him; none of which truly belong to the Gnostic.
And how shall one “judge” the apostate “angels,” who has
become himself an apostate from that forgetfulness of injuries, which
is according to the Gospel? “Why do ye not rather suffer wrong?” he
says; “why are ye not rather defrauded? Yea, ye do wrong and
defraud,”[1292] manifestly by praying against those who transgress in
ignorance, and deprive of the philanthropy and goodness of God, as
far as in you lies, those against whom you pray, “and these your
brethren,”—not meaning those in the faith only, but also the
proselytes. For whether he who now is hostile shall afterwards
believe, we know not as yet. From which the conclusion follows
clearly, if all are not yet brethren to us, they ought to be regarded in
that light. And now it is only the man of knowledge who recognises
all men to be the work of one God, and invested with one image in
one nature, although some may be more turbid than others; and in
the creatures he recognises the operation, by which again he adores
the will of God.
“Know ye not that the unrighteous shall not inherit the kingdom of
God?”[1293] He acts unrighteously who retaliates, whether by deed
or word, or by the conception of a wish, which, after the training of
the Law, the Gospel rejects.
“And such were some of you”—such manifestly as those still are
whom you do not forgive; “but ye are washed,”[1294] not simply as
the rest, but with knowledge; ye have cast off the passions of the
soul, in order to become assimilated, as far as possible, to the
goodness of God’s providence by long-suffering, and by forgiveness
“towards the just and the unjust,” casting on them the gleam of
benignity in word and deeds, as the sun.
The Gnostic will achieve this either by greatness of mind, or by
imitation of what is better. And that is a third cause. “Forgive, and it
shall be forgiven you;” the commandment, as it were, compelling to
salvation through superabundance of goodness.
“But ye are sanctified.” For he who has come to this state is in a
condition to be holy, falling into none of the passions in any way, but
as it were already disembodied and already grown holy without[1295]
this earth.
“Wherefore,” he says, “ye are justified in the name of the Lord.” Ye
are made, so to speak, by Him to be righteous as He is, and are
blended as far as possible with the Holy Spirit. For “are not all things
lawful to me? yet I will not be brought under the power of any,”[1296]
so as to do, or think, or speak aught contrary to the gospel. “Meats
for the belly, and the belly for meats, which God shall destroy,”[1297]
—that is, such as think and live as if they were made for eating, and
do not eat that they may live as a consequence, and apply to
knowledge as the primary end. And does he not say that these are,
as it were, the fleshy parts of the holy body? As a body, the church of
the Lord, the spiritual and holy choir, is symbolized. Whence those,
who are merely called, but do not live in accordance with the word,
are the fleshy parts. “Now” this spiritual “body,” the holy Church, “is
not for fornication.” Nor are those things which belong to heathen life
to be adopted by apostasy from the gospel. For he who conducts
himself heathenishly in the Church, whether in deed, or word, or
even in thought, commits fornication with reference to the Church
and his own body. He who in this way “is joined to the harlot,” that is,
to conduct contrary to the Covenant, becomes another “body,” not
holy, “and one flesh,” and has a heathenish life and another hope.
“But he that is joined to the Lord in spirit” becomes a spiritual body
by a different kind of conjunction.
Such an one is wholly a son, an holy man, passionless, gnostic,
perfect, formed by the teaching of the Lord; in order that in deed, in
word, and in spirit itself, being brought close to the Lord, he may
receive the mansion that is due to him who has reached manhood
thus.
Let the specimen suffice to those who have ears. For it is not
required to unfold the mystery, but only to indicate what is sufficient
for those who are partakers in knowledge to bring it to mind; who
also will comprehend how it was said by the Lord, “Be ye perfect as
your Father, perfectly,”[1298] by forgiving sins, and forgetting injuries,
and living in the habit of passionlessness. For as we call a physician
perfect, and a philosopher perfect, so also, in my view, do we call a
Gnostic perfect. But not one of those points, although of the greatest
importance, is assumed in order to the likeness of God. For we do
not say, as the Stoics do most impiously, that virtue in man and God
is the same. Ought we not then to be perfect, as the Father wills?
For it is utterly impossible for any one to become perfect as God is.
Now the Father wishes us to be perfect by living blamelessly,
according to the obedience of the gospel.
If, then, the statement being elliptical, we understand what is
wanting, in order to complete the section for those who are incapable
of understanding what is left out, we shall both know the will of God,
and shall walk at once piously and magnanimously, as befits the
dignity of the commandment.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like