1. Trang chủ
  2. » Giáo án - Bài giảng

apress dom scripting web design with javascript and the document object model

345 1,6K 2

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề DOM Scripting Web Design with JavaScript and the Document Object Model
Tác giả Jeremy Keith
Trường học Apress
Chuyên ngành Web Design with JavaScript and the Document Object Model
Thể loại Book
Năm xuất bản 2005
Thành phố United States
Định dạng
Số trang 345
Dung lượng 3,14 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Unfortunately, the choice of this name really only had the effect of confusingthe two languages in people’s minds—a confusion that was amplified by the fact that web DOM SCRIPTING: WEB D

Trang 2

DOM Scripting

Web Design with JavaScript and the Document Object Model

Jeremy Keith

Trang 3

DOM Scripting

Web Design with JavaScript and the Document Object Model

Copyright © 2005 by Jeremy Keith All rights reserved No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher

ISBN (pbk): 1-59059-533-5 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY, 10013 Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com, or

visit www.springeronline.com

For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley, CA

94710 Phone 510-549-5930, fax 510-549-5939, e-mail info@apress.com, or visit www.apress.com

The information in this book is distributed on an “as is” basis, without warranty Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or

indirectly by the information contained in this work

The source code for this book is freely available to readers at www.friendsofed.com

in the Downloads section.

Trang 4

For Jessica, my wordridden wife

Trang 5

C O N T E N T S AT A G L A N C E

Foreword xv

About the Author xvii

About the Technical Reviewer xviii

About the Foreword Writer xix

Acknowledgments xx

Introduction xxi

Chapter 1: A Brief History of JavaScript 3

Chapter 2: JavaScript Syntax 13

Chapter 3: The Document Object Model 41

Chapter 4: A JavaScript Image Gallery 57

Chapter 5: Best Practices 77

Chapter 6: Image Gallery Revisited 93

Trang 6

Chapter 8: Enhancing Content 145

Chapter 9: CSS-DOM 177

Chapter 10: Animated Slideshow 207

Chapter 11: Putting It All Together 243

Chapter 12: The Future of DOM Scripting 293

Reference 311

Index 329

vi

Trang 7

C O N T E N T S

Foreword xv

About the Author xvii

About the Technical Reviewer xviii

About the Foreword Writer xix

Acknowledgments xx

Introduction xxi

Chapter 1: A Brief History of JavaScript 3

The origins of JavaScript 4

What is a Document Object Model? 5

The browser wars 6

The D word: DHTML 6

Clash of the browsers 7

Raising the standard 7

Thinking outside the browser 8

The end of the browser wars 8

A new beginning 9

What’s next? 10

Trang 8

Chapter 2: JavaScript Syntax 13

What you’ll need 14

Syntax 16

Statements 16

Comments 16

Variables 18

Data types 20

Strings 20

Numbers 21

Boolean values 22

Arrays 22

Associative arrays 24

Operations 25

Arithmetic operators 25

Conditional statements 27

Comparison operators 29

Logical operators 29

Looping statements 30

while 31

do while 31

for 32

Functions 33

Variable scope 35

Objects 36

Native objects 38

Host objects 38

What’s next? 39

Chapter 3: The Document Object Model 41

D is for document 42

Objects of desire 42

Dial M for model 43

Nodes 45

element nodes 45

text nodes 46

attribute nodes 46

Cascading Style Sheets 47

getElementById 49

getElementsByTagName 50

Taking stock 52

getAttribute 52

setAttribute 54

What’s next? 55

viii

Trang 9

Chapter 4: A JavaScript Image Gallery 57

The markup 58

The JavaScript 61

A DOM diversion 62

Finishing the function 62

Applying the JavaScript 63

Event handlers 63

Expanding the function 65

Introducing childNodes 66

Introducing the nodeType property 67

Adding a description in the markup 68

Changing the description with JavaScript 69

Introducing the nodeValue property 69

Introducing firstChild and lastChild 70

Using nodeValue to update the description 70

What’s next? 74

Chapter 5: Best Practices 77

Please don’t let me be misunderstood 78

Don’t blame the messenger 78

The Flash mob 79

Question everything 80

Graceful degradation 81

The javascript: pseudo-protocol 82

Inline event handlers 82

Who cares? 83

The lessons of CSS 84

Progressive enhancement 85

Unobtrusive JavaScript 86

Backwards compatibility 88

Browser sniffing 90

What’s next? 90

Chapter 6: Image Gallery Revisited 93

A quick recap 94

Does it degrade gracefully? 95

Is the JavaScript unobtrusive? 96

Adding the event handler 97

Checkpoints 97

What’s in a name? 99

Looping the loop 100

Changing behavior 101

Closing it up 102

Share the load 102

C O N T E N T S

ix

Trang 10

Assuming too much 104

Fine-tuning 107

Keyboard access 109

Beware of onkeypress 110

Sharing hooks with CSS 112

DOM Core and HTML-DOM 115

What’s next? 117

Chapter 7: Creating Markup on the Fly 119

document.write 120

innerHTML 122

Pros and cons 125

DOM methods 125

createElement 126

appendChild 127

createTextNode 128

A more complex combination 130

Revisiting the image gallery 132

insertBefore 135

Writing the insertAfter function 136

Using the insertAfter function 137

The finished image gallery 138

Summary 142

What’s next? 143

Chapter 8: Enhancing Content 145

What not to do 146

Making the invisible visible 147

The content 148

HTML or XHTML? 149

The markup 149

The CSS 151

The JavaScript 152

Displaying abbreviations 152

Writing the displayAbbreviations function 153

Creating the markup 155

A browser bomb 161

Displaying citations 164

Writing the displayCitations function 165

Displaying access keys 171

The markup 171

The JavaScript 173

Summary 174

What’s next? 175

x

Trang 11

Chapter 9: CSS-DOM 177

Three sheets to the Web 178

Structure 178

Presentation 178

Behavior 179

Separation 180

The style property 180

Getting styles 182

Inline only 186

Setting styles 188

Knowing when to use DOM styling 189

Styling elements in the node tree 189

Repetitive styling 193

Responding to events 198

className 200

Abstracting a function 203

What’s next? 204

Chapter 10: Animated Slideshow 207

What is animation? 208

Position 208

Time 211

setTimeout 211

Increments 212

Abstraction 215

Practical animation 222

The situation 222

The solution 223

CSS 225

JavaScript 227

A question of scope 231

Refining the animation 233

Final touches 236

Generating markup 238

What’s next? 241

Chapter 11: Putting It All Together 243

The brief 244

Raw materials 244

Site structure 244

Page structure 246

Design 247

CSS 248

Color 250

Layout 251

Typography 254

C O N T E N T S

xi

Trang 12

Markup 255

JavaScript 256

Page highlighting 257

JavaScript slideshow 262

Internal navigation 267

JavaScript image gallery 272

Table enhancements 276

Form enhancements 281

Labels 283

Default values 284

Form validation 286

Summary 290

What’s next? 291

Chapter 12: The Future of DOM Scripting 293

The state of the Web 294

Web browsers 294

Crazy like a Firefox 295

Web designers 296

The three-legged stool 297

The DOM Scripting Task Force 297

Ajax 298

The XMLHttpRequest object 300

An explosion of Ajax 302

Ajax challenges 305

Progressive enhancement with Ajax 305

Hijax 306

The future of Ajax 307

Applications on the Web 308

What’s next? 309

Reference 311

Methods 312

Creating nodes 312

createElement 312

createTextNode 313

Duplicating nodes 314

cloneNode 314

Inserting nodes 316

appendChild 316

insertBefore 317

Removing nodes 318

removeChild 318

Replacing nodes 318

replaceChild 318

Manipulating nodes 319

setAttribute 319

xii

Trang 13

Finding nodes 320

getAttribute 320

getElementById 321

getElementsByTagName 321

hasChildNodes 322

Properties 323

Node properties 323

nodeName 323

nodeType 323

nodeValue 324

Traversing the node tree 325

childNodes 325

firstChild 325

lastChild 326

nextSibling 326

parentNode 327

previousSibling 327

Index 329

C O N T E N T S

xiii

Trang 14

“JavaScript? No way It’s inaccessible, you know Relying on it will make your site unusable,too It’s the root of many an evil pop-up window I mean, it probably even kicked your dogwhen no one was looking.”

Or so I thought

Are you like me, a web designer or developer who has avoided JavaScript on principle? Thereare a lot of us out there, and no wonder With so many examples of bad scripting living on inoutdated web tutorials from the height of the dot-com era, the overwhelming resistance tousing it is no large surprise

Thankfully, there are people out there like Jeremy Keith working to point us back in the rightdirection In this book, he shows us that, hey, it’s not as bad as all that When used properly,with care and attention paid to the traditional JavaScript gotchas, DOM Scripting is a power-ful and even vital addition to the web development toolbox

In fact, the state of DOM Scripting at the moment reminds me of where CSS was in 2002 Up

to that point, CSS had been considered this quirky little web display language that no oneused for anything more than font styling

But then interest in CSS-based layouts exploded, and the tide started to turn High-profilecommercial redesigns by Wired and ESPN, the first of many, triggered a change in opinion Icontributed by launching the CSS Zen Garden in early 2003, a project meant to spark inter-est in the capability of CSS amongst designers By the end of that year, CSS had shifted from

a specialty item to an expected method of development for many organizations

And now we see DOM Scripting sitting at the beginning of a similar curve With high-profileapplications like Google Maps and Flickr recently taking advantage of DOM Scripting, thedemand is growing More than ever, people like you and me are interested in honing ourscripting skills and learning how to make the power of the DOM work for us in ways that willenhance usability, not hinder it

Trang 15

Lucky for us, we now have this book to lead the way And I couldn’t think of a better person

to learn from than Jeremy Keith As a driving force behind the Web Standards Project’sScripting Task Force, he’s on top of all the latest developments in powerful, unobtrusivescripting Besides, I’ve been stealing his code for ages anyway, at least now that it’s in con-venient book form I don’t have to feel so guilty about it

And it is a great book to learn from After stumbling through the first few code examples, Iwas hungry for more After reading through the first chapter, I knew I was hooked JeremyKeith is blessed with the rare ability to explain advanced concepts in simple, easy-to-understand English He takes the time to back up his claims with commonsense examples, sothat you don’t simply know what to do, you also know why you should be doing it

It’s time to toss out the browser sniffing in favor of object detection No more assumingevery visitor has JavaScript enabled either Let’s lose the inline event handlers, once and forall The web is getting an upgrade, and the techniques in this book are going to help it comeabout in a way that benefits everybody

xvi

Trang 16

Jeremy Keith is a web developer living and working in Brighton, England Working with the

web consultancy firm Clearleft (www.clearleft.com), Jeremy enjoys building accessible, gant websites using the troika of web standards: XHTML, CSS, and the DOM His online home

ele-is adactio.com Jeremy ele-is also a member of the Web Standards Project (webstandards.org)where he serves as joint leader of the DOM Scripting Task Force

When he’s not building websites, Jeremy plays bouzouki in the alt.country band Salter Cane(www.saltercane.com) He is also the creator and curator of one of the web’s largest onlinecommunities dedicated to Irish traditional music, The Session (www.thesession.org)

xvii

Trang 17

A B O U T T H E T E C H N I C A L R E V I E W E R

Jon Stephens got his start in the IT and technical writing fields in the mid-1990s by teaching

computers how to operate radio stations (and then teaching humans how to operate thecomputers) He’s been working with Web and Open Source technologies since 1996, andalmost from the beginning of that time gravitated to using JavaScript, both client-side and

server-side as well as PHP, Python, and MySQL He is a co-author of Professional JavaScript, Second Edition (Wrox Press, 2001) and has contributed his JavaScript and DOM scripting

expertise to numerous other books on web technologies as an author or reviewer, including

The JavaScript Programmer’s Reference (Wrox, 2001), Usable Web Menus (glasshaus, 2001), Professional PHP 4 XML Programming (Wrox, 2002), and Constructing Usable Shopping Carts

(glasshaus, 2002; reissued by Apress, 2004) Most recently he was the co-author (with Chad

Russell) of MySQL Database Design and Optimization (Apress, 2004) and is currently working

on PHP 5 Recipes for Apress Jon is a regular contributor to International PHP magazine, for

whom he’s written a couple of articles on DOM scripting in PHP 4 and 5 He’s also been active

on a number of developer websites (including HiveMinds.org and Experts-Exchange.com)

as well as several JavaScript/DOM mailing lists

Jon hung up his freelancer’s hat in 2004 when he accepted a full-time job as a technicalwriter with MySQL AB He helps maintain the MySQL Manual and other MySQL documenta-tion, wrestles with the vagaries of DocBook XML, and hangs out on the MySQL User Forums.Jon is known to become quite excited when occasionally he gets to do some JavaScript orPHP DOM scripting in connection with his job

Having lived most places where one can reasonably live in the USA, Jon migrated in 2002 toAustralia He shares a house in Brisbane’s South End with several cats and computers, both ofwhose numbers constantly fluctuate In his spare time, he likes going to the ocean, finding newplaces to drink coffee, reading the odd detective thriller, and listening to his daughter sing

xviii

Trang 18

Dave Shea is the creator and cultivator of the highly influential CSS Zen Garden website

(www.csszengarden.com) As well as being a member of the Web Standards Project, Dave isthe owner and director of Bright Creative, and he writes about all things Web for his dailyweblog, mezzoblue.com With more than six years of experience working on the Web, Dave

is a leader of the new generation of web designers that believe in responsible web design

xix

Trang 19

I took this idea and presented it to Chris Mills at friends of ED Chris was gracious enough togive me the green light, despite the fact that I had never written a book before Everyone atfriends of ED has been helpful and encouraging I’d particularly like to thank my projectmanager, Beckie Stones, and my copy editor, Julie Smith, for their support and good humor

in dealing with this rookie author

I would never have learned to write a single line of JavaScript if it weren’t for two things Thefirst is the view source option built in to almost every web browser Thank you, view source.The second is the existence of JavaScript giants who have been creating amazing code andexplaining important ideas over the years Scott Andrew, Aaron Boodman, Steve Champeon,Peter-Paul Koch, Stuart Langridge, and Simon Willison are just some of the names that spring

to mind Thank you all for sharing

Thanks to Molly Holzschlag for sharing her experience and advice with me and for giving mefeedback on early drafts Thanks to Derek Featherstone for many a pleasurable JavaScript-laden chat; I like the way your mind works

Extra-special thanks to Aaron Gustafson who provided invaluable feedback and inspirationduring the writing of this book

While I was writing this book, I had the pleasure of speaking at two wonderful events: South

by Southwest in Austin, Texas, and @media in London Thanks to Hugh Forrest and PatrickGriffiths respectively for orchestrating these festivals of geekery that allowed me to meetand befriend the nicest, friendliest bunch of people I could ever hope to call my peers.Finally, I’d like to thank my wife, Jessica Spengler, not only for her constant support, but also forher professional help in proofreading my first drafts Go raibh míle maith agat, a stór mo chroí

xx

Trang 20

This book deals with a programming language, but it isn’t intended for programmers This is

a book for web designers Specifically, this book is intended for standards-aware designerswho are comfortable using CSS and XHTML If that sounds like you, read on

This book is made up of equal parts code and concepts Don’t be frightened by the code: Iknow it might look intimidating at first, but once you’ve grasped the concepts behind thecode, you’ll find yourself reading and writing in a new language Learning a programminglanguage might seem like a scary prospect, but it needn’t be DOM Scripting might appear to

be more verbose than, say, CSS, but once you’ve got the hang of the syntax, you’ll find self armed with a powerful web development tool

your-In any case, the code is there simply to illustrate the concepts I’ll let you in on a secret:nobody memorizes all the syntax and keywords that are part and parcel of any programminglanguage That’s what reference books are for

This isn’t a reference book I’m going to cover the bare minimum of syntax required to get

up and running with JavaScript I’m really going to focus on the ideas behind DOM Scripting

A lot of these ideas might already be familiar to you: graceful degradation, progressiveenhancement, and user-centered design are important concepts in any aspect of front-endweb development

These ideas inform all the code examples given in this book You’ll find scripts for creatingimage galleries, animating slideshows, and enhancing the look and feel of page elements Ifyou want, you can simply cut and paste these examples, but it’s more important to under-stand the hows and whys that lie behind the code

If you’re already using CSS and XHTML to turn your designs into working web pages, thenyou already know how powerful web standards can be Remember the thrill you experiencedwhen you realized you’d never have to use a <font> tag again? Remember when you discov-ered that you could change the design throughout an entire site just by changing one CSSfile? The Document Object Model offers an equal level of power

But with great power comes great responsibility That’s why I’m not just going to show youcool DOM Scripting effects; I’m also going to show you how to use DOM Scripting toenhance your web pages in a usable, accessible way

xxi

Trang 21

To get hold of all the code examples discussed in the book, pay a visit tohttp://www.friendsofed.com and find this book’s page At this site, you can also find outabout all the other great books friends of ED have to offer, on web standards, Flash,Dreamweaver, and much more besides.

Your exploration of DOM Scripting needn’t end when you close this book I’ve set up a site at http://domscripting.com/, where I’m going to continue the discussion of modern,standards-based JavaScript I hope you’ll pay the site a visit In the meantime, enjoy the book

web-xxii

Trang 23

What this chapter covers:

The origins of JavaScriptThe browser warsThe evolution of the DOMThis is an exciting time to be a web designer In recent years, web design has evolved from itschaotic, haphazard roots into a mature design discipline Designers are adopting a standards-based approach to building websites, and the term “web standards” has been coined todescribe the technologies that enable this approach

Whenever designers discuss the subject of web standards, eXtensible HyperText Markup

Language (XHTML) and Cascading Style Sheets (CSS) usually take center stage However,

there’s a third technology, approved by the World Wide Web Consortium (W3C) and ported by all standards-compliant web browsers, called the Document Object Model

sup-(DOM) The DOM allows us to add interactivity to our documents in much the same waythat CSS allow us to add styles

Before looking at the DOM, let’s examine the language that you’ll be using to make yourweb pages interactive The language is JavaScript, and it’s been around for quite some time

The origins of JavaScript

JavaScript was developed by Netscape, in collaboration with Sun Microsystems BeforeJavaScript, web browsers were fairly basic pieces of software capable of displaying hyper-text documents JavaScript was later introduced to add some extra spice to web pages and

to make them more interactive The first version, JavaScript 1.0, debuted in NetscapeNavigator 2 in 1995

At the time of JavaScript 1.0’s release, Netscape Navigator dominated the browser market.Microsoft was struggling to catch up with its own browser, Internet Explorer, and was quick

to follow Netscape’s lead by releasing its own VBScript language, along with a version ofJavaScript called JScript, with the delivery of Internet Explorer 3

As a response to this, Netscape and Sun set about standardizing the language, together

with the European Computer Manufacturers Association (ECMA) The result was

ECMAScript, yet another name for the same language Though the name never reallystuck, we should really be referring to JavaScript as ECMAScript

JavaScript, ECMAScript, JScript—whatever you want to call it—was gaining ground by

1996 Version 3 browsers from Netscape and Microsoft both supported the JavaScript 1.1language to varying degrees

I should point out that JavaScript has nothing to do with Java, a programming languagedeveloped by Sun Microsystems JavaScript was originally going to be called LiveScript

“JavaScript” was probably chosen to make the new language sound like it was in goodcompany Unfortunately, the choice of this name really only had the effect of confusingthe two languages in people’s minds—a confusion that was amplified by the fact that web

DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

4

Trang 24

browsers also supported a form of client-side Java However, while Java’s strength lies in

the fact that it can theoretically be deployed in almost any environment, JavaScript was

always intended for the confines of the web browser

JavaScript is a scripting language This means that unlike a program that does everything

itself, the JavaScript language simply tells the web browser what to do The web browser

interprets the script and does all the work, which is why JavaScript is often compared

unfa-vorably with compiled programming languages like Java and C++ But JavaScript’s relative

simplicity is also its strength Because it has a low barrier to entry, non-programmers who

wanted to cut and paste scripts into their existing web pages quickly adopted the language

JavaScript also offered developers the chance to manipulate aspects of the web browser

For example, the language could be used to manipulate the properties of a browser

window, such as its height, width, and position Addressing the browser’s own properties in

this way can be thought of as a Browser Object Model (BOM) Early versions of JavaScript

also provided a primitive sort of Document Object Model

What is a Document Object Model?

In short, a Document Object Model (DOM) is a way of conceptualizing the contents of a

document

In the real world, we all share something I’ll call a World Object Model We can refer to

objects in our environment using terms like “car,” “house,” and “tree” and be fairly certain

that our terms will be understood That’s because we have mutually agreed upon which

objects the words refer to specifically If I say “The car is in the garage,” it’s safe to assume

that you won’t take that to mean “The bird is in the cupboard.”

Our World Object Model isn’t restricted to tangible objects though—it also applies to

concepts

For instance, I might refer to “the third house on the left,” when giving you directions For

that description to make sense, the concepts of “third” and “left” must be understood If I

give that description to somebody who can’t count, or who can’t tell left from right, then

the description is essentially meaningless, whether or not the words have been

under-stood In reality, because people agree on a conceptual world model, very brief

descrip-tions can be full of meaning I can be fairly sure that others share my concepts of “left”

and “third.”

It’s the same situation with web pages Early versions of JavaScript offered developers the

ability to query and manipulate some of the actual contents of web documents—mostly

images and forms Because the terms “images” and “forms” had been predefined,

JavaScript could be used to address “the third image in the document” or “the form

named ‘details,’” as shown:

document.images[2]

document.forms['details']

5 1

Trang 25

This first, tentative sort of Document Object Model is often referred to as DOM Level 0 Inthose early, carefree days, the most common usage of DOM Level 0 was for imagerollovers and some client-side form validation But when the fourth generation ofbrowsers from Netscape and Microsoft appeared, the DOM really hit the fan.

The browser wars

Netscape Navigator 4 (NN4) was released in June 1997, and by October of that year,Internet Explorer 4 (IE4) had also been released Both browsers promised many improve-ments on previous versions, along with many additions to what could be accomplishedwith JavaScript, using a greatly expanded DOM Web designers were encouraged to

test-drive the latest buzzword: DHTML.

The D word: DHTML

DHTML was short for dynamic HTML Not a technology in and of itself, DHTML was ashorthand term for describing the marriage of HTML, CSS, and JavaScript The thinkingbehind DHTML went like this:

You could use HTML to mark up your web page into elements

You could use CSS to style and position those elements

You could use JavaScript to manipulate and change those styles on the fly.DHTML referred to the combination of those three techniques Using DHTML, complexanimation effects suddenly became possible Let’s say you used HTML to mark up a pageelement like this:

<div id="myelement">This is my element</div>

You could then use CSS to apply positioning styles like this:

#myelement {position: absolute;

left: 50px;

top: 100px;

}Then, using JavaScript, you could change the left and top styles of myelement to move itaround the page Well, that was the theory anyway

Unfortunately for developers, both browsers used different, incompatible DOMs.Although the browser manufacturers were promoting the same ends, they eachapproached the DOM issue in completely different ways

DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

6

Trang 26

Clash of the browsers

The Netscape DOM made use of proprietary elements called layers These layers were

given unique IDs and then addressed through JavaScript like this:

document.layers['myelement']

Meanwhile, the Microsoft DOM would address the same element like this:

document.all['myelement']

The differences didn’t end there Let’s say you wanted to find out the left position

of myelement and assign it to the variable xpos In Netscape Navigator 4 you would do it

like this:

var xpos = document.layers['myelement'].left;

Here’s how you would do the same thing in Internet Explorer 4:

var xpos = document.all['myelement'].leftpos;

This was clearly a ridiculous situation Developers had to fork their code to accomplish any

sort of DOM scripting In effect, many scripts were written twice, once for NN4 and once

for IE4 Convoluted browser sniffing was often required to serve up the correct script

DHTML promised a world of possibilities But anybody who actually attempted to use it

discovered a world of pain instead It wasn’t long before DHTML became a dirty

(buzz)word The technology quickly garnered a reputation for being both over hyped and

overly difficult to implement

Raising the standard

While the browser manufacturers were busy engaging in their battle for supremacy, and

using competing DOMs as weapons in their war, the W3C was quietly putting together a

standardized Document Object Model Fortunately, the browser vendors were able to set

aside their mutual animosity Netscape, Microsoft, and other browser manufacturers

worked together with the W3C on the new standard and DOM Level 1 was completed in

October 1998

Going back to our example, let’s take a look at how the new standardized DOM would

tackle the same situation Remember, we have a <div> with the ID myelement and we’re

trying to ascertain the value that has been applied to its left position so that we can store

that value as the variable xpos Here’s the syntax we would use:

var xpos = document.getElementById('myelement').style.left

At first glance, that might not appear to be an improvement over the non-standard,

pro-prietary DOMs However, the standardized DOM is far more ambitious in its scope

7 1

Trang 27

While the browser manufacturers simply wanted some way to manipulate web pages with

JavaScript, the W3C proposed a model that could be used by any programming language

to manipulate any document written in any markup language.

Thinking outside the browser

The DOM is what’s known as an Application Programming Interface (API) APIs are tially conventions that have been agreed upon by mutual consent Real-world equivalentswould be things like

essen-Morse codeInternational time zonesThe periodic table of the elementsAll of these things are standards, and they make it easier for people to communicate andcooperate In situations where a single convention hasn’t been agreed upon, the result isoften disastrous Remember, competition between metric and imperial measurements hasresulted in at least one failed Mars mission

In the world of programming, there are many different languages, but there are many ilar tasks That’s why APIs are so handy Once you know the standard, you can apply it inmany different environments The syntax may change depending on the language you’reusing, but the convention remains the same

sim-So, while I focus specifically on using the DOM with JavaScript in this book, your newknowledge of the DOM will also be very useful if you ever need to parse an XML docu-ment using a programming language like PHP or Python

The W3C defines the DOM as

“A platform- and language-neutral interface that will allow programs and scripts todynamically access and update the content, structure, and style of documents.”

The independence of the standardized DOM, together with its powerful scope, places it headand shoulders above the proprietary DOMs created by the bickering browser manufacturers

The end of the browser wars

Microsoft won the battle for browser market-share supremacy Ironically, the clash ofcompeting DOMs and proprietary markup had little effect on the final outcome InternetExplorer was destined to win simply by virtue of the fact that it came pre-installed on allPCs running the Windows operating system

The people who were hit hardest by the browser wars were web designers Cross-browserdevelopment had become a nightmare As well as the discrepancies in JavaScript imple-mentations that I mentioned earlier, the two browsers also had very different levels of sup-port for CSS Creating style sheets and scripts that worked on both browsers became akind of black art

DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

8

Trang 28

A backlash began against the proprietary stance of the browser manufacturers A

group was formed calling itself the Web Standards Project, or the WaSP for short

(http://webstandards.org/) The first task that the WaSP undertook was to encourage

browser makers to adopt W3C recommendations—the very same recommendations that

the browser manufacturers had helped draft

Whether it was due to pressure from the WaSP or the result of internal company decisions,

there was far greater support for web standards in the next generation of web browsers

A new beginning

Internet Explorer 5 shipped with built-in support for WC3’s standardized DOM, while also

maintaining support for the old, proprietary Microsoft DOM

Netscape decided to make a clean break and released a browser that had next to nothing in

common with NN4 Netscape Navigator 6 even skipped a version number, and it used a

completely different rendering engine with far, far greater CSS support It also supported the

standardized DOM, but without any backwards compatibility for the old Netscape DOM

Subsequent releases from both Netscape and Microsoft improved on previous

incarna-tions with increased support for web standards Unfortunately, development of Internet

Explorer has stagnated at version 6 This is a pity, as some problems still remain with the

browser’s implementation of CSS Support for DOM Level 1, however, is rock solid

In the meantime, other browsers have appeared on the scene When Apple debuted its

Safari web browser in 2003, there was no question that it would follow the DOM

standards Firefox, Mozilla, and Camino, all based on the same open-source rendering

engine as Netscape 6 and 7, have excellent support for the DOM Opera and Konquerer

also offer great DOM support

Over 95% of the browsers in active use today have built-in support for the DOM The

browser wars of the late nineties appear to be well and truly behind us Although no

single browser has implemented the W3C DOM perfectly, all modern browsers cover

about 95% of the specifications This means there’s a huge amount that we can accomplish

without having to worry about branching code

The stagnated development of Internet Explorer notwithstanding, life has improved

greatly for web designers Instead of writing scripts with forked code served up with

com-plicated browser sniffing, we are now in a position to write something once and publish it

everywhere As long as we follow the DOM standards, we can be sure that our scripts will

work almost universally

9 1

Trang 29

What’s next?

One thing you should definitely take away from my brief JavaScript history lesson is thatdifferent browsers used to accomplish the same tasks in different ways This inescapablefact dominated not just the writing of JavaScript scripts, it also dictated how books aboutJavaScript were written

Any JavaScript books aimed at demonstrating how to learn the language by example oftenhad to show the same scripts written in different ways for different browsers Just like thecode found on most websites, the examples in most JavaScript books were full of browsersniffing and code branching Similarly, technical reference books on JavaScript couldn’tsimply contain lists of functions and methods They also had to document which functionsand methods were supported by which browsers

The situation has changed now Thanks to the standardization of the DOM, differentbrowsers do the same things in much the same way This means that when I’m showingyou how to do something using JavaScript and the Document Object Model, we won’t getsidetracked by browser inconsistencies

I am going to try to avoid mentioning any specific browsers in this book

I’m also not going to use the term DHTML any more The term always worked better as amarketing buzzword than as a technical description For one thing, it sounds confusinglylike another flavor of HTML or XHTML Also, the term comes with a lot of baggage If youmention DHTML to anyone who tried using it in the late nineties, you’ll have a hard timeconvincing them that it’s a straightforward, standardized technology now

DHTML was supposed to refer to the combination of (X)HTML, CSS, and JavaScript, but inactual fact, what binds these things together is the DOM If we need any term to describethis process, let’s use something more accurate While the term DHTML could be used torefer to browser-specific coding, it doesn’t seem right to try to apply the same term to

standards-based coding DOM Scripting is a more accurate way to describe the

manipula-tion of documents and style sheets using the W3C Document Object Model

Whereas DHTML referred only to web documents, DOM Scripting can be used in tion with any marked-up document using any language that supports the DOM API In thecase of web documents, the ubiquity of JavaScript makes it the best choice for DOMScripting

conjunc-Before I get down to the nitty-gritty of DOM Scripting, I’m going to give you a briefrefresher in JavaScript syntax, which is what you’ll find in the next chapter

DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

10

Trang 31

What this chapter covers:

StatementsVariables and arraysOperators

Conditional statements and looping statementsFunctions and objects

This chapter is a brief refresher in JavaScript syntax, taking on the most important concepts

What you’ll need

You don’t need any special software to write JavaScript All you need is a plain text editorand a web browser

Code written in JavaScript must be executed from a document written in (X)HTML Thereare two ways of doing this You can place the JavaScript between <script> tags within the

<head> of the document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

Trang 32

If you’d like to try the examples in this chapter, go ahead and create two files in a text editor.

First, create a simple bare-bones HTML or XHTML file You can call it something like

test.html Make sure that it contains a <script> tag in the <head> that has a src attribute

with a value like example.js That’s the second file you can create in your text editor

Your test.html file should look something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

You can copy any of the examples in this chapter and write them into example.js None

of the examples are going to be particularly exciting, but they may be illuminating

In later chapters, I’ll be showing you how to use JavaScript to alter the behavior and

con-tent of your document For now, I’ll be using simple dialog boxes to display messages

Whenever you change the contents of example.js, you can test its effects by reloading

test.html in a web browser The web browser will interpret the JavaScript code immediately

Programming languages are either interpreted or compiled Languages like Java or C++

require a compiler A compiler is a program that translates the source code written in a

high-level language like Java into a file that can be executed directly by a computer

Interpreted languages don’t require a compiler—they just need an interpreter instead

With JavaScript, in the context of the World Wide Web, the web browser does the

inter-preting The JavaScript interpreter in the browser executes the code directly from the

source Without the interpreter, the JavaScript code would never get executed

If there are any errors in the code written in a compiled language, those errors will pop up

when the code is compiled In the case of an interpreted language, errors won’t become

apparent until the interpreter executes the code

Although compiled languages tend to be faster and more portable than interpreted

lan-guages, they often have a fairly steep learning curve

One of the nice things about JavaScript is that it’s relatively easy to pick up Don’t let that

fool you though: JavaScript is capable of some pretty complex programming operations

For now, let’s take a look at the basics

15 2

Trang 33

English is an interpreted language By reading and processing these words that I havewritten in English, you are acting as the interpreter As long as I follow the grammaticalrules of English, my writing can be interpreted correctly These grammatical rules include

structural rules known as syntax.

Every programming language, just like every written language, has its own syntax.JavaScript has a syntax that is very similar to that of other programming languages like Javaand C++

Statements

A script written in JavaScript, or any other programming language, consists of a series of

instructions These are called statements These statements must be written with the right

syntax in order for them to be interpreted correctly

Statements in JavaScript are like sentences in English They are the building blocks of anyscript

Whereas English grammar demands that sentences begin with a capital letter and end with

a period, the syntax of JavaScript is much more forgiving You can simply separate ments by placing them on different lines:

state-first statement second statement

If you place a number of statements on the same line, you must separate them with colons like this:

semi-first statement; second statement;

However, it is good programming practice to place a semicolon at the end of every ment even if they are on different lines:

ments to be ignored by the JavaScript interpreter These are called comments.

DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

16

Trang 34

Comments can be very useful when you want to keep track of the flow of your code They

act like sticky notes, helping you to keep track of what is happening in your script

JavaScript allows you to indicate a comment in a number of different ways For example, if

you begin a line with two forward slashes, that line will be treated as a comment:

// Note to self: comments are good

If you use this notation, you must put the slashes at the start of each comment line This

won’t work, for instance:

// Note to self:

comments are good

Instead, you’d need to write

// Note to self:

// comments are good

If you want to comment out multiple lines like that, you can place a forward slash and an

asterisk at the start of the comment block and an asterisk and forward slash at the end:

/* Note to self:

comments are good */

This is useful when you need to insert a long comment that will be more readable when it

is spread over many lines

You can also use HTML-style comments, but only for single lines In other words, JavaScript

treats <!— the same way that it treats //:

<!— This is a comment in JavaScript

In HTML, you would need to close the comment with —>:

<!— This is a comment in HTML —>

JavaScript would simply ignore the closing of the comment, treating it as part of the

com-ment itself

Whereas HTML allows you to split comments like this over multiple lines, JavaScript

requires the comment identifier to be at the start of each line

Because of the confusing differences in how this style of comment is treated by JavaScript,

I don’t recommend using HTML-style comments Stick to using two forward slashes for

single-line comments and the slash-asterisk notation for multi-line comments

17 2

Trang 35

In our everyday lives there are some things about us that are fixed and some things thatare changeable My name and my birthday are fixed My mood and my age, on the other

hand, will change over time The things that are subject to change are called variables.

My mood changes depending on how I’m feeling Suppose I had a variable with the namemood I could use this variable to store my current state of mind Regardless of whether thisvariable has the value “happy” or “sad”, the name of the variable remains the same: mood

I can change the value as often as I like

Likewise, my age might currently be 33 In one year’s time, my age will be 34 I could use

a variable named age to store how old I am and then update age on my birthday When

I refer to age now, it has the value 33 In one year’s time, the same term will have thevalue 34

Giving a value to a variable is called assignment I am assigning the value “happy” to the

variable mood I am assigning the value 33 to the variable age

This is how you would assign these variables in JavaScript:

mood = "happy";

age = 33;

When a variable has been assigned a value, we say that the variable contains the value.

The variable mood now contains the value “happy” The variable age now contains the value

33 You could then display the values of these two variables in annoying pop-up alertwindows by using the statements

alert(mood);

alert(age);

Here is an example of the value of the variable called mood:

Here is an example of the value of the variable called age:

DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

18

Trang 36

We’ll get on to doing useful things with variables later on in the book, don’t you worry!

Notice that you can jump right in and start assigning values to variables without introducing

them first In many programming languages, this isn’t allowed Other languages demand

that you first introduce, or declare, any variables.

In JavaScript, if you assign a value to a variable that hasn’t yet been declared, the variable is

declared automatically Although declaring variables beforehand isn’t required in JavaScript,

it’s still good programming practice Here’s how you would declare mood and age:

var mood;

var age;

You don’t have to declare variables separately You can declare multiple variables at the

same time:

var mood, age;

You can even kill two birds with one stone by declaring a variable and assigning it a value

at the same time:

var mood = "happy";

var age = 33;

You could even do this:

var mood = "happy", age = 33;

That’s the most efficient way to declare and assign variables It has exactly the same

meaning as doing this:

var mood, age;

mood = "happy";

age = 33;

The names of variables, along with just about everything else in JavaScript, are

case-sensitive The variable mood is not the same variable as Mood, MOOD or mOOd These

statements would assign values to two different variables:

var mood = "happy";

MOOD = "sad";

The syntax of JavaScript does not allow variable names to contain spaces or punctuation

characters (except for the dollar symbol, $) The next line would produce a syntax error:

var my mood = "happy";

Variable names can contain letters, numbers, dollar symbols, and underscores In order to

avoid long variables looking all squashed together, and to improve readability, you can use

underscores in variable names:

var my_mood = "happy";

19 2

Trang 37

The text “happy” in that line is an example of a literal A literal is something that is

liter-ally written out in the JavaScript code Whereas the word var is a keyword and my_mood isthe name of a variable, the text “happy” doesn’t represent anything other than itself Toparaphrase Popeye, “It is what it is!”

Data types

The value of mood is a string literal, whereas the value of age is a number literal These aretwo different types of data, but JavaScript makes no distinction in how they are declared

or assigned Some other languages demand that when a variable is declared, its data type

is also declared This is called typing.

Programming languages that require explicit typing are called strongly typed languages Because typing is not required in JavaScript, it is a weakly typed language This means that

you can change the data type of a variable at any stage

The following statements would be illegal in a strongly typed language but are perfectlyfine in JavaScript:

var age = "thirty three";

age = 33;

JavaScript doesn’t care whether age is a string or a number

Now let’s review the most important data types that exist within JavaScript

Strings

Strings consist of zero or more characters Characters include letters, numbers, tion marks, and spaces Strings must be enclosed in quotes You can use either singlequotes or double quotes Both of these statements have the same result:

punctua-var mood = 'happy';

var mood = "happy";

Use whichever one you like, but it’s worth thinking about what characters are going to becontained in your string If your string contains the double-quote character, then it makessense to use single quotes to enclose the string If the single-quote character is part of thestring, you should probably use double quotes to enclose the string:

var mood = "don't ask";

If you wanted to write that statement with single quotes, you would need to ensure thatthe apostrophe (or single quote) between the n and the t is treated as part of the string

In this case, the single quote needs to be treated the same as any other character, rather

than as a signal for marking the end of the string This is called escaping In JavaScript,

escaping is done using the backslash character:

var mood = 'don\'t ask';

DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

20

Trang 38

Similarly, if you enclose a string with double quotes, but that string also contains a

double-quote character, you can use the backslash to escape the double-double-quote character within

the string:

var height = "about 5'10\" tall";

These backslashes don’t actually form part of the string You can test this for yourself by

adding this to your example.js file and reloading test.html:

var height = "about 5'10\" tall";

alert(height);

Here’s an example of an output of a variable using backslashes to escape characters:

Personally, I like to use double quotes Whether you decide to use double or single quotes,

it’s best to be consistent If you switch between using double and single quotes all the

time, your code could quickly become hard to read

Numbers

If you want a variable to contain a numeric value, you don’t have to limit yourself to whole

numbers JavaScript also allows you to specify numbers to as many decimal places as you

want These are called floating-point numbers:

var age = 33.25;

You can also use negative numbers A minus sign at the beginning of a number indicates

that it’s negative:

Trang 39

Boolean values

Another data type is Boolean.

Boolean data has just two possible values: true or false Let’s say I wanted a variable tostore one value for when I’m sleeping and another value for when I’m not sleeping I coulduse the string data type and assign it values like “sleeping” or “not sleeping”, but it makesmuch more sense to use the Boolean data type:

var sleeping = true;

Boolean values lie at the heart of all computer programming At a fundamental level, allelectrical circuits use only Boolean data: either the current is flowing or it isn’t Whetheryou think of it in terms of “true and false”, “yes and no”, or “one and zero”, the importantthing is that there can only ever be one of two values

Boolean values, unlike string values, are not enclosed in quotes There is a differencebetween the Boolean value false and the string value “false”

This will set the variable married to the Boolean value true:

var married = true;

In this case, married is a string containing the word “true”:

var married = "true";

Arrays

Strings, numbers, and Boolean values are all examples of scalars If a variable is a scalar,

then the variable can only ever have one value at any one time If you want to use a

vari-able to store a whole set of values, then you need an array.

An array is a grouping of multiple values under the same name Each one of these values

is an element of the array For instance, you might want to have a variable called beatles

that contains the names of all four members of the band at once

In JavaScript, you declare an array by using the Array keyword You can also specify the

number of elements that you want the array to contain This number is the length of the

array:

var beatles = Array(4);

Sometimes you won’t know in advance how many elements an array is eventually going tohold That’s OK Specifying the number of elements is optional You can just declare anarray with an unspecified number of elements:

var beatles = Array();

DOM SCRIPTING: WEB DESIGN WITH JAVASCRIPT AND THE DOCUMENT OBJECT MODEL

22

Trang 40

Adding elements to an array is called populating When you populate an array, you specify

not just the value of the element, but also where the element comes in the array This is the

index of the element Each element has a corresponding index The index is contained in

square brackets:

array[index] = element;

Let’s start populating our array of Beatles We’ll go in the traditional order of John, Paul,

George, and Ringo Here’s the first index and element:

beatles[0] = "John";

I know it might seem counterintuitive to start with an index of zero instead of one, but I’m

afraid that’s just the way that JavaScript works It’s easy to forget this Many novice

pro-grammers have fallen into this common pitfall when first using arrays

Here’s how we’d declare and populate our entire beatles array:

var beatles = Array(4);

beatles[0] = "John";

beatles[1] = "Paul";

beatles[2] = "George";

beatles[3] = "Ringo";

You can now retrieve the element “George” in your script by referencing the index 2

(beatles[2]) It might take a while to get used to the fact that the length of the array is

four when the last element has an index of three That’s an unfortunate result of arrays

beginning with the index number zero

That was a fairly long-winded way of populating an array You can take a shortcut by

pop-ulating your array at the same time that you declare it When you are poppop-ulating an array

in a declaration, separate the values with commas:

var beatles = Array("John","Paul","George","Ringo");

An index will automatically be assigned for each element The first index will be zero, the

next will be one, etc So referencing beatles[2] will still give us “George”

You don’t even have to specify that you are creating an array Instead, you can use square

brackets to group the initial values together:

var beatles = ["John","Paul","George","Ringo"];

Still, it’s good to get into the habit of using the Array keyword when you declare or

pop-ulate an array Your scripts will be more readable and it will be easy to spot arrays at a

glance

The elements of an array don’t have to be strings You can store Boolean values in an array

You can also use an array to store a series of numbers:

var years = Array(1940,1941,1942,1943);

23 2

Ngày đăng: 28/04/2014, 16:20

TỪ KHÓA LIÊN QUAN