Free Download PDF Books, HTML5 And CSS3 All In One For Dummies, HTML5 Tutorial Book

HTML5 And CSS3 All In One For Dummies, HTML5 Tutorial Book

HTML HTML5 ReadOnline

Summary of Contents

  • Page 1

    Making actionURI(http://www.a-pdf.com/?tr-demo):Everything actionURI(http://www.a-pdf.com/?tr-demo):Easier!3rdactionURI(http://www.a-pdf.com/?tr-demo):EditionHTML5 andCSS3ALL-IN-ONEFOR<£>AWiley BrandgBOOKS4/'"28* * '•Creating the HTMLFoundation•Styling with CSS•Building Layouts ...

  • Page 2

    Start with FREE Cheat SheetsCheat Sheets include•Checklists•Charts•CommonInstructions•AndOtherGoodStuff!Get Smart at Dummies.com Dummies.com makes your life easier with 1,000s of answers on everything from removing wallpaper to using the latest version of Windows. Check out our•Videos...

  • Page 3

    HTML5 and CSS3 ALL -IN- ONE3rd Editionby Andy Harriswww.freepdf-books.com

  • Page 4

    HTML5 and CSS3 All-in-One For Dummies®, 3rd EditionPublished by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, actionURI(http://www.wiley.com):www.wiley.comCopyright © 2014 by John Wiley & Sons, Inc., Hoboken, New JerseyMedia and software compilation copyright ...

  • Page 5

    Contents at a Glance 29,Introduction 29, ................................................................ 29,1 35,Part I: Creating 35,the HTML Foundation 35, ........................... 35,7 37,Chapter 1: Sound HTML 37,Foundations 37, .............................................................

  • Page 6

    555,Part V: Server-Side 555,Programming with PHP 555, ............... 555,527 557,Chapter 1: Getting Started on the 557,Server 557, .................................................................... 557,529 577,Chapter 2: PHP and HTML 577,Forms 577, ...........................................

  • Page 7

    Table of Contents 29,Introduction 29, ................................................................. 29,1 29,About This Book 29, .............................................................................................. 29,1 30,Foolish Assumptions 30, .......................................

  • Page 8

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionvi 72,Finding a Good Web Developer’s 72,Browser 72, ................................................. 72,44 72,A little ancient history 72, ......................................................................... 72,44 74,Overview of the pro...

  • Page 9

    Table of Contentsvii 121,Using built-in effects 121, ............................................................................ 121,93 125,Other effects you can use 125, ................................................................... 125,97 126,Batch processing 126, .........................

  • Page 10

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionviii 165,Hex education..................................................................................... 165,137 167,Using the web-safe 167,color palette 167, ...................................................... 167,139 168,Choosing Your C...

  • Page 11

    Table of Contentsix 210,Using 210, classes 210, ...................................................................................... 210,182 210,Combining classes 210, ............................................................................. 210,182 212,Introducing div and span 212, ........

  • Page 12

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionx 263,Overriding styles 263, ................................................................................ 263,235 264,Precedence of style definitions 264, ........................................................ 264,236 265,Managing Browser ...

  • Page 13

    Table of Contentsxi 313,Chapter 2: Building Floating Page Layouts 313, 313, . . . . . . . . . . . . . . . . . . . . . 313, .285 313,Creating a Basic Two-Column Design 313, ....................................................... 313,285 313,Designing the page 313, ..................................

  • Page 14

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionxii 362,Writing the HTML 362, .............................................................................. 362,334 363,Adding the CSS 363, ................................................................................... 363,335 364,Creating...

  • Page 15

    Table of Contentsxiii 403,Chapter 2: Talking to the 403,Page 403, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403, .375 403,Understanding the Document 403,Object Model 403, ........................................... 403,375 403,Previewing the DOM 403, ........................

  • Page 16

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionxiv 446,Managing Errors with a Debugger 446, ............................................................. 446,418 448,Debugging with the interactive console 448, ......................................... 448,420 450,Debugging strategies 450, .....

  • Page 17

    Table of Contentsxv 498,Working with Regular 498,Expressions 498, ........................................................... 498,470 501,Introducing regular expressions 501, ...................................................... 501,473 503,Using characters in regular expressions 503, ..........

  • Page 18

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionxvi 555,Part V: Server-Side 555,Programming with PHP 555, ................ 555,527 557,Chapter 1: Getting Started on the 557,Server 557, . . . . . . . . . . . . . . . . . . . . . . . 557, .529 557,Introducing Server-Side Programming 557, .........

  • Page 19

    Table of Contentsxvii 615,Chapter 4: Working with 615,Arrays 615, 615, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615, .587 615,Using One-Dimensional Arrays 615, .................................................................. 615,587 615,Creating an array 615, ................

  • Page 20

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionxviii 667,Chapter 7: Exceptions and 667,Objects 667, . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667, .639 667,Object-Oriented Programming in 667,PHP 667, ...................................................... 667,639 668,Building a...

  • Page 21

    Table of Contentsxix 716,Selecting Data from Your 716,Tables 716, ............................................................... 716,688 717,Selecting only a few fields 717, ................................................................. 717,689 718,Selecting a subset of records 718, .........

  • Page 22

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionxx 760,Counting the advantages 760,of inner joins 760, .......................................... 760,732 761,Building a view to encapsulate 761,the join 761, .......................................... 761,733 761,Managing Many-to-Many 761,Jo...

  • Page 23

    Table of Contentsxxi 810,Using $(document).ready( ) 810, ............................................................. 810,782 811,Alternatives to document.ready 811, ...................................................... 811,783 811,Investigating the jQuery Object 811, ...........................

  • Page 24

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionxxii 857,Importing the files 857, .............................................................................. 857,829 858,Making a resizable element 858, .............................................................. 858,830 858,Adding themes...

  • Page 25

    Table of Contentsxxiii 911,Chapter 7: Going Mobile 911, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911, .883 911,Thinking in Mobile 911, ....................................................................................... 911,883 913,Building a Responsive 913,S...

  • Page 26

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionxxiv 961,Chapter 2: Planning Your Sites 961, 961, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961, .933 961,Creating a Multipage Web Site 961, ................................................................... 961,933 962,Plan...

  • Page 27

    Table of Contentsxxv 1007,Introducing Gimp 1007, ......................................................................................... 1007,979 1008,Creating an image 1008, .............................................................................. 1008,980 1008,Painting tools 1008, .......

  • Page 28

    HTML5 and CSS3 All-In-One For Dummies, 3rd Editionxxviwww.freepdf-books.com

  • Page 29

    IntroductionI love the Internet, and if you picked up this book, you probably do, too. The Internet is dynamic, chaotic, exciting, interesting, and useful, all at the same time. The web is pretty fun from a user’s point of view, but that’s only part of the story. Perhaps the best part of the...

  • Page 30

    Foolish Assumptions2 ✓ How to write programs on the server: Today’s web is powered by pro-grams on web servers. You’ll discover the powerful PHP language and figure out how to use it to create powerful and effective sites. ✓ How to harness the power of data: Every web developer eventually...

  • Page 31

    How This Book Is Organized3If you’re curious about AJAX, you can read about what it is, how it works, and how to use it to add functionality to your site. You’ll also read about a very powerful and easy AJAX library that can add tremendous functionality to your bag of tricks.I wrote this book...

  • Page 32

    New for the Third Edition4 ✓ Book I: Creating the HTML Foundation — Web development incorpo-rates a lot of languages and technologies, but HTML is the foundation. Here I show you HTML5, the latest incarnation of HTML, and describe how it’s used to form the basic skeleton of your pages. ✓ ...

  • Page 33

    Icons Used in This Book5 ✓ Focus on HTML5: The first edition of the book used HTML4, the second edition used XHTML, and this edition uses HTML5. I’m very excited about HTML5 because it’s easier to use than either of the older versions, and quite a bit more powerful. ✓ Integration with CSS...

  • Page 34

    Beyond the Book6Beyond the BookYou can find additional features of this book online. Visit the web to find these extras: ✓ Companion website:actionURI(http://www.aharrisbooks.net/haio): www.aharrisbooks.net/haio This is my primary site for this book. Every single example in the book is up and ...

  • Page 35

    actionURI(http://www.dummies.com):Visit actionURI(http://www.dummies.com):www.dummies.comactionURI(http://www.dummies.com): for more great content online.Part ICreating the HTML Foundationwww.freepdf-books.com

  • Page 36

    Contents at a Glance Contents at a GlanceChapter 1: Sound HTML Foundations . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9Creating a Basic Page .........................................................................................................9Understanding the HTML in the Basic...

  • Page 37

    Chapter 1: Sound HTML FoundationsIn This Chapter✓ Creating a basic web page✓ Understanding the most critical HTML tags✓ Setting up your system to work with HTML✓ Viewing your pagesT his chapter is your introduction to building web pages. Before this slim chapter is finished, you’ll have...

  • Page 38

    Creating a Basic Page10 Don’t use a word processor like Microsoft Word or Mac TextEdit. These are powerful tools, but they don’t save things in the right format. The way these tools do things like centering text and changing fonts won’t work on the web. I promise that you’ll figure out h...

  • Page 39

    Understanding the HTML in the Basic Page11Book I Chapter 1Sound HTML Foundations5. Load your page into the browser. You can do this a number of ways. You can use the browser’s File menu to open a local file, or you can simply drag the file from your Desktop (or wherever) to the open browser wi...

  • Page 40

    Meeting Your New Friends, the Tags12 ✦ It works on all computers. The main point of HTML is to have a univer-sal format. Any computer should be able to read and write it. The plain-text formatting aids in this. ✦ It describes what documents mean. HTML isn’t really designed to indicate how a...

  • Page 41

    Meeting Your New Friends, the Tags13Book I Chapter 1Sound HTML Foundationsthe browser which language the page will be written in. Because I write in English, I’m specifying with the code “en.” Some books teach you to write your HTML tags in uppercase letters. This was once a standard, but ...

  • Page 42

    Meeting Your New Friends, the Tags14course, through <h6> where <h2> indicates a heading slightly less impor-tant than <h1>, <h3> is less important than <h2>, and so on. Beginners are sometimes tempted to make their first headline an <h1> tag and then use an &l...

  • Page 43

    Setting Up Your System15Book I Chapter 1Sound HTML FoundationsSetting Up Your SystemYou don’t need much to make web pages. Your plain text editor and a web browser are about all you need. Still, some things can make your life easier as a web developer.Displaying file extensionsThe method discus...

  • Page 44

    Setting Up Your System16 3. De-select filename extensions. If this button is checked, file extensions are shown (which is what you want.) (See Figure 1-2.) Note this is the opposite of Windows 7’s behavior. Although my demonstration uses Windows 7 and 8, the technique is similar in older vers...

  • Page 45

    Setting Up Your System17Book I Chapter 1Sound HTML Foundationsuse) available directly on the Desktop. That way, you can quickly edit any web page by dragging it to the Desktop. When you use more sophis-ticated editors than Notepad, you’ll want links to them, too. ✦ Get another web browser. Yo...

  • Page 46

    18Book I: Creating the HTML Foundationwww.freepdf-books.com

  • Page 47

    Chapter 2: It’s All About ValidationIn This Chapter✓ Introducing the concept of valid pages✓ Using a doctype✓ Setting the character set✓ Meeting the W3C validator✓ Fixing things when they go wrong✓ Using HTML Tidy to clean your pagesW eb development is undergoing a revolution. As th...

  • Page 48

    Somebody Stop the HTML Madness!20to handle all that complexity for them. Although these editing programs introduced new features that made things easier upfront, these tools also made code almost impossible to change without the original editor. Web developers began thinking they couldn’t desig...

  • Page 49

    Book I Chapter 2It’s All About ValidationSomebody Stop the HTML Madness!21 ✦ Everything’s lowercase. Some people wrote HTML in uppercase, some in lowercase, and some just did what they felt like. It was inconsistent and made it harder to write browsers that could read all the variations. ...

  • Page 50

    Somebody Stop the HTML Madness!22The browsers also promise to follow a particular standard. If your page validates to a given standard, any browser that validates to that same standard can reproduce your document correctly, which is a big deal.The most important validator is the W3C validator a...

  • Page 51

    Book I Chapter 2It’s All About ValidationValidating Your Page23Validation might sound like a big hassle, but it’s really a wonderful tool because sloppy HTML code can cause lots of problems. Worse, you might think everything’s okay until somebody else looks at your page, and suddenly, the ...

  • Page 52

    Validating Your Page24</h2> </body></html>The code looks okay, but actually has a number of problems. Aesop may have been a great storyteller, but from this example, it appears he was a sloppy coder. The mistakes can be hard to see, but trust me, they’re there. The question is...

  • Page 53

    Book I Chapter 2It’s All About ValidationValidating Your Page25Aesop visits W3CTo find out what’s going on with this page, pay a visit to the W3C validator actionURI(http://validator.w3.org):at http://validator.w3.org. Figure 2-3 shows me visiting this site and uploading a copy of oxWheels1....

  • Page 54

    Validating Your Page26Examining the overviewBefore you look at the specific complaints, take a quick look at the web page the validator sends you. The web page is chock-full of handy information. The top of the page tells you a lot of useful things: ✦ Result: This is really the important thing....

  • Page 55

    Book I Chapter 2It’s All About ValidationValidating Your Page27 ✦ Scan the next couple of errors. Sometimes, one mistake shows up as more than one error. Look over the next couple of errors, as well, to see if they provide any more insight; sometimes, they do. ✦ Try a change and revalidate....

  • Page 56

    Validating Your Page28<head> <meta charset="UTF-8"> <!-- oxWheels1.html --> <!-- note this page has deliberate errors! Please see the text and oxWheelsCorrect.html for a corrected version.--> </head><body><title>The Oxen and the Wheels<...

  • Page 57

    Book I Chapter 2It’s All About ValidationValidating Your Page29 4. Note the current first error position. Before you submit the modified page to the validator, make a mental note of the position of the current first error. Right now, the validator’s first complaint is on line 12, column 7. I ...

  • Page 58

    Validating Your Page30This explains why browsers might be confused about how to display the headings. It isn’t clear whether this code should be displayed in H1 or H2 format, or perhaps with no special formatting at all. It’s much better to know the problem and fix it than to remain ignorant ...

  • Page 59

    Book I Chapter 2It’s All About ValidationValidating Your Page31 Figure 2-7: HTML Tidy is an alternative to the W3C validator. Figure 2-8: Tidy fixes the page, but the fix is a little awkward.Unlike W3C’s validator, Tidy actually attempts to fix your page. Figure 2-8 displays how Tidy sugg...

  • Page 60

    Validating Your Page32 ✦ Tidy got confused by the headings. Tidy correctly fixed the level one heading, but it had trouble with the level two heading. It removed all the tags, so it’s valid, but the text intended to be a level two heading is just sort of hanging there. ✦ Sometimes, the inde...

  • Page 61

    Chapter 3: Choosing Your ToolsIn This Chapter✓ Choosing a text editor✓ Using a dedicated HTML editor✓ Comparing common browsersW eb development is a big job. You don’t go to a construction site with-out a belt full of tools (and a cool hat), and the same thing is true with web development...

  • Page 62

    How About Online Site Builders?34 ✦ Code maintenance: The commercial editors that concentrate on visual design tend to create pretty unmanageable code. If you find there’s something you need to change by hand, it’s pretty hard to fix the code. ✦ Vendor lock-in: These tools are written by ...

  • Page 63

    35Alternative Web Development ToolsBook I Chapter 3Choosing Your Toolssome cost money to use. I go over how to install and modify a CMS (and even build your own) in Book VIII. A CMS system can be nice because it allows you to build a website visually without any special tools or knowledge.The CMS...

  • Page 64

    Picking a Text Editor36Fortunately, you have several choices, as the following sections reveal.Tools to avoid unless you have nothing elseA text editor may be a simple program, but that doesn’t mean they’re all the same. Some programs have a history of causing problems for beginners (and expe...

  • Page 65

    Book I Chapter 3Choosing Your ToolsPicking a Text Editor37 Figure 3-1: Notepad++ has many of the features you need in a text editor. Notepad++ has a lot of interesting features. Here are a few highlights: ✦ Syntax highlighting: Notepad++ can recognize key HTML terms and put different types of...

  • Page 66

    Picking a Text Editor38geditOne simple but effective editor available free for all major operating sys-tems is gedit. It is the default editor for many versions of Linux, but you can download it for Mac and Windows fractionURI(http://projects.gnome.org/gedit/):om http://projects.gnome.org/actionU...

  • Page 67

    Book I Chapter 3Choosing Your ToolsPicking a Text Editor39Both might seem obscure and difficult to modern sensibilities, but they still have passionate adherents, even in the Windows community. (Besides, Linux is more popular than ever!)VI and VIMVI stands for VIsual Editor. That name seems stran...

  • Page 68

    Picking a Text Editor40because it has all the features you might need. If you don’t already know VI, it’s probably more efficient for you to start with a more standard text editor, such as Notepad++.EmacsThe other popular editor from the UNIX world is Emacs. Like VI, you prob-ably don’t nee...

  • Page 69

    Book I Chapter 3Choosing Your ToolsPicking a Text Editor41 Emacs has an astonishing number of options and a nonstandard interface, so it can be challenging for beginners. However, those who have made the investment (like me) swear by it.My personal choice: Komodo EditPersonally I really like Komo...

  • Page 70

    Picking a Text Editor42 ✦ Multiple file support: Your first few web pages will be single documents, but most websites incorporate many pages. Komodo allows you to have several pages at once and to compare any two pages at the same time. ✦ Page Preview: Just use ctrl-K-V to preview the current...

  • Page 71

    Book I Chapter 3Choosing Your ToolsPicking a Text Editor43As you begin coding, the basic features of Komodo Edit are more than enough for your needs. However, you’ll soon become more adept at coding, you may want some tools to improve your efficiency. My favorite add-on for Komodo is a tool cal...

  • Page 72

    Finding a Good Web Developer’s Browser44 ✦ SynEdit: Much like Notepad++ and very popular with web developers ✦ Scintilla: Primarily a programming editor, but has nice support for HTML coding ✦ jEdit: A popular text editor written in Java with nice features, but some developers consider it...

  • Page 73

    Book I Chapter 3Choosing Your ToolsFinding a Good Web Developer’s Browser45browser to support, write two versions of the page, or stick with the more limited set of features common to both browsers.Netscape 6.0 was a technical disappointment, and Microsoft capitalized, earning a nearly complete...

  • Page 74

    Finding a Good Web Developer’s Browser46 standards will be acceptable. The real question today isn’t which browser the user prefers, but does the user have a browser that’s reasonably com-plaint with today’s standards?Overview of the prominent browsersThe browser is the primary tool of th...

  • Page 75

    Book I Chapter 3Choosing Your ToolsFinding a Good Web Developer’s Browser47 ✦ Multi-platform support: IE works only on the Windows operating system, so it isn’t available to Mac or Linux users. Even if you’re a Windows-only developer, your users may use something else, so you need to know...

  • Page 76

    Finding a Good Web Developer’s Browser48 ✦ Page Outline: A well-designed web page is created in outline form, with various elements nested inside each other. The elements view allows you to see the web page in this format, with the ability to collapse and expand elements to see your page’s ...

  • Page 77

    Book I Chapter 3Choosing Your ToolsFinding a Good Web Developer’s Browser49display graphics. Auditory browsers read the contents of web pages. They were originally intended for people with visual disabilities, but people with-out any disabilities often use them as well. Fire Vox is a variant of...

  • Page 78

    50Book I: Creating the HTML Foundationwww.freepdf-books.com

  • Page 79

    Chapter 4: Managing Information with Lists and TablesIn This Chapter✓ Understanding basic lists✓ Creating unordered, ordered, and nested lists✓ Building definition lists✓ Building basic tables✓ Using rowspan and colspan attributesY ou’ll often need to present large amounts of organize...

  • Page 80

    Making a List and Checking It Twice52 Figure 4-1: An unordered list of web browsers.✦ Each item begins a new line. When a list item is displayed, it’s shown on a new line.These characteristics help you see that you have a list, but they’re just default behaviors. Defining something as a l...

  • Page 81

    Book I Chapter 4Managing Information with Lists and TablesMaking a List and Checking It Twice53The code for the unordered list is pretty straightforward:<!doctype html><html lang="en"><head> <meta charset="UTF-8"><title>basicUL.html</title&g...

  • Page 82

    Making a List and Checking It Twice54Building the ordered listThe code for basicOL.html is remarkably similar to the previous unordered list:<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>basicOL.html</title></h...

  • Page 83

    Book I Chapter 4Managing Information with Lists and TablesMaking a List and Checking It Twice55In this example, there’s an unordered list with only two elements. Each of these elements contains an <h3> heading and an ordered list. The page han-dles all this data in a relatively clean way ...

  • Page 84

    Making a List and Checking It Twice56 <li>Sam</li> <li>Misty</li> </ol> </li> </ul> </body></html>Here are a few things you might notice in this code listing: ✦ There’s a large <ul> set surrounding...

  • Page 85

    Book I Chapter 4Managing Information with Lists and TablesMaking a List and Checking It Twice57 ✦ End at the left margin. If you finish the page and you’re not back at the left margin, you’ve forgotten to end something. Proper indentation makes seeing your page organization easy. Each eleme...

  • Page 86

    Making a List and Checking It Twice58Here’s the code for basicDL.html:<!DOCTYPE HTML><html lang="en-US"> <head> <meta charset="UTF-8"> <title>BasicDL.html</title> </head> <body> <h1>Basic Definition List</h...

  • Page 87

    Book I Chapter 4Managing Information with Lists and TablesBuilding Tables59As you can see, the definition list uses three tag pairs: ✦ <dl></dl> defines the entire list. ✦ <dt></dt> defines each definition term. ✦ <dd></dd> defines the definition data.Def...

  • Page 88

    Building Tables60<head> <meta charset="UTF-8"> <title>basicTable.html</title></head><body> <h1>A Basic Table</h1> <h2>HTML Super Heroes</h2> <table border = "1"> <tr> <th>...

  • Page 89

    Book I Chapter 4Managing Information with Lists and TablesBuilding Tables61and some don’t. You can set the border value to 0 or to a larger number. The larger number makes a bigger border, as shown in Figure 4-6. Although this method of making table borders is perfectly fine, I show a much mor...

  • Page 90

    Building Tables62<tr> <th></th> <th></th> <th></th></tr>Place the text you want shown in the table headers between the <th> and </th> elements. The contents appear in the order they’re defined. Headings don’t have to be on the top...

  • Page 91

    Book I Chapter 4Managing Information with Lists and TablesBuilding Tables63 4. Copy and paste the empty row to make as many rows as you need. 5. Save, view, and validate. Be sure everything looks right and validates properly before you put a lot of effort into adding data. 6. Populate the table w...

  • Page 92

    Building Tables64 <td>train minions</td> <td>train minions</td> <td>train minions</td> <td rowspan = "2">world domination</td> </tr> <tr> <th>Evening</th> <t...

  • Page 93

    Book I Chapter 4Managing Information with Lists and TablesBuilding Tables65The Design Traps cell spans over two normal columns. The colspan attri-bute tells how many columns this cell will take. The Improve Hideout cell has a colspan of 3.The Morning row still takes up six columns. The <th>...

  • Page 94

    Building Tables66 ✦ Tables aren’t meant for layout. Tables are designed for data presenta-tion, not layout. To make tables work for layout, you have to do a lot of sneaky hacks, such as tables nested inside other tables or invisible images for spacing. ✦ The code becomes complicated fast. T...

  • Page 95

    Chapter 5: Making Connections with LinksIn This Chapter✓ Understanding hyperlinks✓ Building the anchor tag✓ Recognizing absolute and relative links✓ Building internal links✓ Creating lists of linksT he basic concept of the hyperlink is common today, but it was a major breakthrough back ...

  • Page 96

    Making Your Text Hyper68 Figure 5-1: You can click the links to visit the other sites. ✦ The browser needs to know where to go. When the user clicks the link, the browser is sent to some address somewhere on the Internet. Sometimes that address is visible on the page, but it doesn’t need to ...

  • Page 97

    Making Your Text Hyper69Book I Chapter 5Making Connections with Links </head> <body> <h1>Some of my favorite sites</h1> <h2>Wikipedia</h2> <p> One of my favorite websites is called <a href = "http://www.wikipedia.org...

  • Page 98

    Making Your Text Hyper70 <a href = "http://www.wikipedia.org">wikipedia.</a> ✦ The anchor tag itself: The anchor tag is simply the <a></a> pair. You don’t type the entire word anchor, just the a. ✦ The hypertext reference ( href) attribute: Almost al...

  • Page 99

    Making Lists of Links71Book I Chapter 5Making Connections with Links ✦ Subdomain: Everything between the host name (usually www) and the domain name (often .com) is the subdomain. This is used so that large organizations can have multiple servers on the same domain. For exam-ple, my department...

  • Page 100

    Making Lists of Links72 ✦ Links: Each list item contains a link. The link has a reference (which you can’t see immediately) and linkable text (which is marked like an ordi-nary link). ✦ Descriptive text: After each link is some ordinary text that describes the link. Writing some text to acc...

  • Page 101

    Working with Absolute and Relative References73Book I Chapter 5Making Connections with LinksThe indentation is interesting here. Each list item contains an anchor and some descriptive text. To keep the code organized, web developers tend to place the anchor inside the list item. The address some...

  • Page 102

    74Working with Absolute and Relative ReferencesThe page isn’t so interesting on its own, but it isn’t meant to stand alone. When you click one of the links, you go to a brand-new page. Figure 5-4 shows what happens when you click the market link. Figure 5-4: The market page lets you move back...

  • Page 103

    Working with Absolute and Relative References75Book I Chapter 5Making Connections with LinksMost of the code is completely familiar. The only thing surprising is what’s not there. Take a closer look at one of the links: <a href = "market.html">home</a>.</li>...

  • Page 104

    76Book I: Creating the HTML Foundationwww.freepdf-books.com

  • Page 105

    Chapter 6: Adding Images, Sound, and VideoIn This Chapter✓ Understanding the main uses of images✓ Choosing an image format✓ Creating inline images✓ Using IrfanView and other image software✓ Changing image sizes✓ Adding audio clips✓ Working with videoY ou have the basics of text, bu...

  • Page 106

    Adding Images to Your Pages78The techniques you read about in this chapter apply to all type of images, but a couple of specific applications (such as backgrounds and bullets) use CSS. For details on using images in CSS, see Book II, Chapter 4.Linking to an imageThe easiest way to incorporate ima...

  • Page 107

    Book I Chapter 6Adding Images, Sound, and VideoAdding Images to Your Pages79 See Chapter 5 of this minibook for a discussion of anchor tags if you need a refresher.This works fine for most images because the image is displayed directly in the browser. You can use this anchor trick with any kind o...

  • Page 108

    Adding Images to Your Pages80image indicates how to get back to the web page. Most users know to click the browser’s Back button, but don’t assume all users know what to do.Adding inline images using the <img> tagThe alternative to providing links to images is to embed your images into ...

  • Page 109

    Book I Chapter 6Adding Images, Sound, and VideoAdding Images to Your Pages81The image (img) tag is the star of this page. This tag allows you to grab an image file and incorporate it into the page directly. The image tag is a one-shot tag. It doesn’t end with </img>. Instead, use the />...

  • Page 110

    Choosing an Image Manipulation Tool82 The alt attribute is required on all images.Additionally, the <img> tag is an inline tag, so it needs to be embedded inside a block-level tag, like a <p> or <li>.Choosing an Image Manipulation ToolYou can’t just grab any old picture off yo...

  • Page 111

    Book I Chapter 6Adding Images, Sound, and VideoChoosing an Image Manipulation Tool83one corner. This actual picture came out at 2,816 pixels wide by 2,112 pixels tall. You only see a small corner of the image because the screen shots for this book are taken at 1024×768 pixels. Less than a quarte...

  • Page 112

    Choosing an Image Manipulation Tool84The new version of the image is the size and file format I need, it looks just as good, and it weighs a much more reasonable 88 kilobytes. That’s 2 per-cent of the original image size. Although this picture is a lot smaller than the original image, it still ...

  • Page 113

    Book I Chapter 6Adding Images, Sound, and VideoChoosing an Image Format85 ✦ Cropping: You may want only a small part of the original picture. A crop-ping tool allows you to extract a rectangular region from an image. ✦ Filters: You may find it necessary to modify your image in some way. You m...

  • Page 114

    Choosing an Image Format86JPG/JPEGThe JPG format (also called JPEG) is a relatively old format designed by the Joint Photographic Experts Group. (Get it? JPEG!) It works by throwing away data that’s less important to human perception. Every time you save an image in the JPG format, you lose a l...

  • Page 115

    Book I Chapter 6Adding Images, Sound, and VideoChoosing an Image Format87The color palette works like a paint-by-number set where an image has a series of numbers printed on it, and each of the paint colors has a corre-sponding number. What happens in a GIF image is similar. GIF images have a lis...

  • Page 116

    Choosing an Image Format88 Figure 6-6: This statue is a GIF with trans­parency. Animated GIFs were overused in the early days of the web, and many now consider them the mark of an amateur. Nobody really thinks that animated mailbox is cute anymore. Look ahead to Book IV, Chapter 7 for the more...

  • Page 117

    Book I Chapter 6Adding Images, Sound, and VideoChoosing an Image Format89 ✦ No software patents: The underlying technology of PNG is completely open source, with no worries about whether somebody will try to enforce a copyright down the road. ✦ True alpha transparency: The PNG format has a mo...

  • Page 118

    Manipulating Your Images90JavaScript code. You can find a great number of free-to-use SVG images at actionURI(http://openclipart.org/):http://openclipart.org/.Summary of web image formatsAll these formats may seem overwhelming, but choosing an image format is easy because each format has its own ...

  • Page 119

    Book I Chapter 6Adding Images, Sound, and VideoManipulating Your Images91 Figure 6-7: IrfanView can save in all these formats. Don’t use spaces in your filenames. Your files may move to other computers on the Internet, and some computers have trouble with spaces. It’s best to avoid spaces a...

  • Page 120

    Manipulating Your Images92 Figure 6-8: IrfanView’s Resize/Resample Image dialog box. 5. Save the resulting image as a new file. When you make an image smaller, you lose data. That’s perfectly fine for the version you put on the web, but you should hang on to the original large image in case...

  • Page 121

    Book I Chapter 6Adding Images, Sound, and VideoManipulating Your Images93 If your image is too dark or too bright, you may be tempted to use the Brightness feature to fix it. The Gamma Correction feature described later in this section is more useful for this task. ✦ Contrast: You usually use t...

  • Page 122

    Manipulating Your Images94Here’s a rundown of some of the effects, including when you would use them: ✦ None: Just for comparison purposes, Figure 6-11 shows the ship image without any filters turned on. I’ve exaggerated the effects for illustration purposes, but it may still be difficult...

  • Page 123

    Book I Chapter 6Adding Images, Sound, and VideoManipulating Your Images95 Figure 6-12: The Blur filter reduces contrast. Figure 6-13: The Sharpen filter increases contrast. If you believe crime shows on TV, you can take a blurry image and keep applying a sharpen filter to read a license plate...

  • Page 124

    Manipulating Your Images96low contrast. You can use the Enhance Colors dialog box to change the gray embossed image to a more appealing color. ✦ Oil Paint: This filter applies a texture reminiscent of an oil painting to an image, as shown in Figure 6-15. It can sometimes clean up a picture and...

  • Page 125

    Book I Chapter 6Adding Images, Sound, and VideoManipulating Your Images97 Figure 6-16: The image appears to stick up from the page like a button. ✦ 3D Button: This feature can be used to create an image, similar to Figure 6-16, that appears to be a button on the page. This will be useful lat...

  • Page 126

    Manipulating Your Images98open-source alternative that does almost as much. See Book VIII, Chapter 4 for more about using Gimp for image processing.Batch processingOften, you’ll have a lot of images to modify at one time. IrfanView has a wonderful batch-processing tool that allows you to work o...

  • Page 127

    Book I Chapter 6Adding Images, Sound, and VideoWorking with Audio99 5. Specify the output directory. If you want to put the new images in the same directory as the input files, click the Use This Directory as Output button. If not, choose the directory where you want the new images to go. 6. In t...

  • Page 128

    Working with Audio100Figure 6-19 demonstrates a page with a simple audio file. Figure 6-19: This page has a song embedded in it. It’s quite easy to add audio to a web page in HTML5 with the new <audio> tag. Here’s the code for creating this page:<!doctype html><html lang=&quo...

  • Page 129

    Book I Chapter 6Adding Images, Sound, and VideoAdding Video101The best way to be sure the sound plays is to supply two different formats. I’ve found that including both Ogg and MP3 formats ensures my audio will play on all major browsers.To add an audio file to your page, follow these steps: 1...

  • Page 130

    Adding Video102 As with any intellectual property, be sure you have the permission of the file’s original owner. Just because you can embed a video into your web page doesn’t mean you should do so.Figure 6-20 shows a page with a simple video embedded in it. Figure 6-20: This page has a vide...

  • Page 131

    Book I Chapter 6Adding Images, Sound, and VideoAdding Video103 Video files are extremely large, and they can make your website seem much slower to users. They also are cumbersome to move to a web server. For this reason, many web developers prefer to upload videos to a service like YouTube and si...

  • Page 132

    104 Book I: Creating the HTML Foundationwww.freepdf-books.com

  • Page 133

    Chapter 7: Creating FormsIn This Chapter✓ Adding forms to your pages✓ Creating input and password text boxes✓ Building multi-line text inputs✓ Making list boxes and check boxes✓ Building groups of radio buttons✓ Using HTML5 form elements✓ Creating buttonsH TML gives you the ability ...

  • Page 134

    You Have Great Form106 Figure 7-1: Form elements allow user interaction. The formDemo.html page shows the following elements: ✦ A form: A container for form elements. Although the form element itself isn’t usually a visible part of the page (like the body tag), it could be with appropriate C...

  • Page 135

    You Have Great Form107Book I Chapter 7Creating Forms ✦ Labels: Many form elements have a small text label associated with them. Although labels are not required, they can make a form easier to style with CSS and easier for the user. ✦ Fieldsets and legends: These set off parts of the form. Th...

  • Page 136

    You Have Great Form108 Figure 7-2: This form has a legend and labels. A fieldset is a special element used to supply a visual grouping to a set of form elements.The form still doesn’t look very good, I admit, but that’s not the point. Like all HTML tags, the form elements aren’t about desc...

  • Page 137

    Building Text-Style Inputs109Book I Chapter 7Creating Forms <p> <label>Phone</label> <input type = "text" /> </p> </fieldset> </form> </body></html>The form has these elements: ✦ The <for...

  • Page 138

    Building Text-Style Inputs110To make a basic text input, you need a form and an input element. Adding a label so that the user knows what he’s supposed to enter into the text box is also common. Here’s the code:<!DOCTYPE html><html lang = "en-US"> <head> <...

  • Page 139

    Building Text-Style Inputs111Book I Chapter 7Creating Forms ✦ value : This attribute determines the default value of the text box. If you leave this attribute out, the text field begins empty.Text fields can also have other attributes, which aren’t used as often, such as ✦ size : This att...

  • Page 140

    Building Text-Style Inputs112 Figure 7-4: Enter the secret pass-word. . . . The password field offers virtually no meaningful security. It protects the user from spy satellites glancing over his shoulder to read a password, but that’s about it. The open standards of HTML and the programming...

  • Page 141

    Building Text-Style Inputs113Book I Chapter 7Creating Forms </p> <p> <label> Please enter the sum total of Western thought. Be brief. </label> </p> <p> <textarea id = "txtAnswe...

  • Page 142

    Building Text-Style Inputs114Creating Multiple Selection ElementsSometimes, you want to present the user with a list of choices and then have the user pick one of these elements. HTML has a number of interesting ways to do this.Making selectionsThe drop-down list is a favorite selection tool of w...

  • Page 143

    Building Text-Style Inputs115Book I Chapter 7Creating Forms <head> <meta charset = "UTF-8"> <title>basicSelect.html</title> </head> <body> <form action = ""> <p> <label>What is your favorite color?&l...

  • Page 144

    Building Text-Style Inputs116 Select boxes don’t require the drop-down behavior. If you want, you can specify the number of rows to display with the size attribute. In this case, the number of rows you specify will always be visible on the screen.Building check boxesCheck boxes are used when yo...

  • Page 145

    Building Text-Style Inputs117Book I Chapter 7Creating Forms<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>checkBoxes.html</title> </head> <body> <form action = ""> &...

  • Page 146

    Building Text-Style Inputs118 Figure 7-8: You can choose only one of these radio buttons. ✦ They have to be in a group. Radio buttons make sense only in a group context. The point of a radio button is to interact with its group. ✦ They all have the same name! Each radio button has its own I...

  • Page 147

    Pressing Your Buttons119Book I Chapter 7Creating Forms value = "100" />Too much </p> <p> <input type = "radio" name = "radPrice" id = "rad200" value = &...

  • Page 148

    Pressing Your Buttons120 <head> <meta charset = "UTF-8"> <title>buttons.html</title> </head> <body> <h1>Button Demo</h1> <form action = ""> <fieldset> <legend> input-style but...

  • Page 149

    Pressing Your Buttons121Book I Chapter 7Creating Forms ✦ This type of button is for client-side programming. This type of code resides on the user’s computer. I discuss client-side programming with JavaScript in Book IV.Building a Submit buttonSubmit buttons are usually used in server-side pr...

  • Page 150

    New Form Input Types122 <button type = "button"> button tag </button>The <button> tag acts more like a standard HTML tag, but it can also act like a Submit button. Here are the highlights: ✦ The type attribute determines the style. You can set ...

  • Page 151

    New Form Input Types123Book I Chapter 7Creating Forms <input type="date" id = "date" /> Figure 7-10: Newer browsers have special inputs — here I’m picking a color. You can restrict the dates allowed to a specific range by applying the min and ma...

  • Page 152

    New Form Input Types124The official full date and time format returned from the various date and time elements is a specialized code:yyyy-mm-ddThh:mm+ff:ggEach of the characters in the code describe a part of the date and time: ✓ yyyy: Four digits for the year. ✓ - (dash): Must be placed betw...

  • Page 153

    New Form Input Types125Book I Chapter 7Creating FormsSome browsers pop up the standard calendar control. When the user selects a date (or a week), only the year and week will be returned. Other browsers will simply validate for the proper format: <input type = "week" ...

  • Page 154

    New Form Input Types126All values can be integer or floating point. However, current browsers which support this tag (Opera and Chrome) do not seem to validate as well with floating-point values as they do with integer values. For more control of numeric input, consider the range input type, desc...

  • Page 155

    New Form Input Types127Book I Chapter 7Creating FormsLike the other new input types, there is no penalty for using the search ele-ment in browsers that do not support it. The fall-back is a plain text input.Note that the search element doesn’t actually do any searching. If you want to actually...

  • Page 156

    128 Book I: Creating the HTML Foundationwww.freepdf-books.com

  • Page 157

    actionURI(http://www.dummies.com/extras/html5css3aio):Visit actionURI(http://www.dummies.com/extras/html5css3aio):www.dummies.com/extras/html5css3aioactionURI(http://www.dummies.com/extras/html5css3aio): for more on using HTML entities.Part IIStyling with CSSwww.freepdf-books.com

  • Page 158

    Contents at a Glance Contents at a GlanceChapter 1: Coloring Your World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .131Now You Have an Element of Style ................................................................................131Specifying Colors in CSS .....................

  • Page 159

    Chapter 1: Coloring Your WorldIn This Chapter✓ Introducing the style element✓ Adding styles to tags✓ Modifying your page dynamically✓ Specifying foreground and background colors✓ Understanding hex colors✓ Appreciating HSL colors✓ Developing a color schemeH TML does a good job of set...

  • Page 160

    Now You Have an Element of Style132 Figure 1-1: This page is in color! Nothing in the HTML code provides color information. What makes this page different from plain HTML pages is a new section that I’ve stashed in the header. Take a gander at the code to see what’s going on (interesting par...

  • Page 161

    Book II Chapter 1Coloring Your WorldNow You Have an Element of Style133The secret is the new <style></style> pair I put in the header area: <style type = "text/css"> body { color: yellow; background-color: red; } h1 { colo...

  • Page 162

    Specifying Colors in CSS134the HTML elements (and other things, too, but not today). The selector for the body is designated like this: body { ✦ Use braces ({}) to enclose the style rules. Each style’s rules are enclosed in a set of braces. Similar to many programming languages, braces m...

  • Page 163

    Book II Chapter 1Coloring Your WorldSpecifying Colors in CSS135chapter, in the section “Creating Your Own Color Scheme,” you find out how to use special numeric designators to choose colors.) Each approach has its advantages.Using color namesColor names seem like the easiest solution, and, f...

  • Page 164

    Specifying Colors in CSS136ColorHex ValueOlive#808000Yellow#FFFF00Navy#000080Blue#0000FFTeal#008080Aqua#00FFFFObviously, I can’t show you actual colors in this black-and-white book, so I added a simple page to this book’s companion website that displays all the named colors. Check namedColors...

  • Page 165

    Book II Chapter 1Coloring Your WorldSpecifying Colors in CSS137111111111111111100000000. Ack! There has to be an easier way to handle all those binary values. That’s why we use hexadecimal notation. Read on. . . .Figure 1-2 shows a page which allows you to pick colors with red, green, and b...

  • Page 166

    Specifying Colors in CSS138Table 1-2 Hex Representation of Base Ten NumbersDecimal (Base 10)Hex (Base 16)0011223344556677889910A11B12C13D14E15FThe ordinary digits 0–9 are the same in hex as they are in base 10, but the values from 10–15 (base ten) are represented by alphabetic characters in ...

  • Page 167

    Book II Chapter 1Coloring Your WorldSpecifying Colors in CSS139 ✦ Hex color values usually begin with a pound sign. To warn the browser that a value will be in hexadecimal, the value is usually preceded with a pound sign (#). So, yellow is #FFFF00.Working with colors in hex may seem really cra...

  • Page 168

    Choosing Your Colors140DescriptionRedGreenBlue999999666666333333Very dark000000To pick a web-safe value from this chart, determine how much of each color you want. A bright red will have red turned on all the way (FF) with no green (00) and no blue (00), making #FF0000. If you want a darker red, ...

  • Page 169

    Book II Chapter 1Coloring Your WorldChoosing Your Colors141Starting with web-safe colorsThe webSafe.html program works by letting you quickly enter a web-safe value. To make red, press the FF button in the red column. The blue and green values have the default value of 00, so the background is r...

  • Page 170

    Choosing Your Colors142 You’ll discover many more CSS elements you can modify throughout Books II and III but for now, stick to color and background-color. 5. Specify the color values with color names or hex color values.Changing CSS on the flyThe Chrome web browser has an especially cool tric...

  • Page 171

    Book II Chapter 1Coloring Your WorldCreating Your Own Color Scheme143 You can modify the CSS of any element as long as some sort of rule has been saved. 10. Copy and paste any style rules you want to keep. Modifications made in the web developer toolbar are not permanent. If you find colors or...

  • Page 172

    Creating Your Own Color Scheme144To describe a color using HSL, you specify three characteristics of a color using numeric values: ✦ Hue: The basic color. The color wheel is broken into a series of hues. These are generally middle of the road colors that can be made brighter (closer to white) a...

  • Page 173

    Book II Chapter 1Coloring Your WorldCreating Your Own Color Scheme145Using HSL colors in your pagesYou can assign an HSL value wherever you use colors in your CSS. As an exam-ple, look at HSLcolors.html on the companion website. (I do not show it here because the color differences are too subtle...

  • Page 174

    Creating Your Own Color Scheme146 5. Determine the saturation. Saturation is measured as a percentage. Saturation of 0% indicates a grayscale (somewhere between black and white) whereas Saturation of 100% is a fully saturated color with no grayscale. You need to include the percent sign as part ...

  • Page 175

    Book II Chapter 1Coloring Your WorldCreating Your Own Color Scheme147The Color Scheme Designer has several features, such as ✦ The color wheel: This tool may bring back fond memories of your elemen-tary school art class. The wheel arranges the colors in a way familiar to artists. You can click...

  • Page 176

    Creating Your Own Color Scheme148 3. Adjust your scheme. The main schemes are picked using default settings for saturation and value. The Adjust Scheme tab allows you to modify the saturation and value settings to get much more control of your color scheme. You can also adjust the level of contr...

  • Page 177

    Chapter 2: Styling TextIn This Chapter✓ Introducing fonts and typefaces✓ Specifying the font family✓ Determining font size✓ Understanding CSS measurement units✓ Managing other font characteristics✓ Using the font rule to simplify font stylesW eb pages are still primarily a text-based ...

  • Page 178

    Setting the Font Family150 <head> <meta charset = "UTF-8"> <title>comicHead.html</title> <style type = "text/css"> h1 { font-family: "Comic Sans MS"; } </style> </head> <body> <h1&g...

  • Page 179

    Book II Chapter 2Styling TextSetting the Font Family151If you run exactly the same page on an iPad, you might see the result shown in Figure 2-2. Figure 2-2: On an iPad, the heading might not be the same font! The specific font Comic Sans MS is installed on Windows machines, but the MS stands f...

  • Page 180

    Setting the Font Family152 Figure 2-3: Here are all the generic fonts. The generic fonts really are families of fonts: ✦ Serif: These fonts have those little serifs (the tiny cross strokes that enhance readability). Print text (like the paragraph you’re reading now) tends to use serif fonts,...

  • Page 181

    Book II Chapter 2Styling TextSetting the Font Family153 Figure 2-4: Windows and the iPad disagree on fantasy. Macs display yet another variation because the fonts listed here aren’t actual fonts. Instead, they’re virtual fonts. A standards-compliant browser promises to select an appropriate ...

  • Page 182

    The Curse of Web-Based Fonts154WindowsMacLinuxComic Sans MSComic Sans MSTSCu_ComicCourier NewCourier NewNimbus Mono LGeorgiaGeorgiaNimbus Roman No9 LLucida ConsoleMonacoPalatinoPalatinoFreeSerifTahomaGenevaKalimatiTimes New RomanTimesFreeSerifTrebuchet MSHelveticaFreeSansVerdanaVerdanaKalimatiYou...

  • Page 183

    Book II Chapter 2Styling TextThe Curse of Web-Based Fonts155can call for a specific font, but that font isn’t displayed unless it’s already installed on the user’s computer.Say I have a cool font called Happygeek. (I just made that up. If you’re a font designer, feel free to make a font c...

  • Page 184

    The Curse of Web-Based Fonts156 Figure 2-5: This page includes a couple of embedded fonts. The @font-face style does not work like most CSS elements. It doesn’t apply markup to some part of the page. Instead, it defines a new CSS value that can be used in other markup. Specifically, it allows ...

  • Page 185

    Book II Chapter 2Styling TextThe Curse of Web-Based Fonts157 h1 { font-family: Miama; font-size: 300%; } h2 { font-family: spray; } </style> </head> <body> <h1>Embedded Font Demo</h1> <h2>Here's another cu...

  • Page 186

    The Curse of Web-Based Fonts158Using images for headlinesGenerally, you should use standard fonts for the page’s main content, so having a limited array of fonts isn’t such a big problem. Sometimes, though, you want to use fonts in your headlines. You can use a graphical editor, like GIMP, to...

  • Page 187

    Book II Chapter 2Styling TextThe Curse of Web-Based Fonts159 4. Use any font you want. You don’t have to worry about whether the user has the font because you’re not sending the font, just an image composed with the font. 5. Create a separate image for each headline. This particular exercis...

  • Page 188

    Specifying the Font Size160 </p> </body></html>This technique is a nice compromise between custom graphics and ordinary HTML as follows: ✦ You have great control of your images. If you’re skilled with your graphics tool, you can make any type of image you want act as a h...

  • Page 189

    Book II Chapter 2Styling TextSpecifying the Font Size161web browsers frequently change the size of text. A cellphone-based browser displays text differently than one on a high-resolution LCD panel. Further, most browsers allow the user to change the size of all the text on the screen. Use Ctrl++ ...

  • Page 190

    Specifying the Font Size162 Figure 2-7: You can easily modify font sizes in your pages. Absolute measurement unitsMany times, you need to specify the size of something in CSS. Of course, font size is one of these cases. The different types of measurement have different implications. It’s impor...

  • Page 191

    Book II Chapter 2Styling TextSpecifying the Font Size163Pixels (px)Pixels refer to the small dots on the screen. You can specify a font size in pixels, although that’s not the way it’s usually done. For one thing, different monitors make pixels in different sizes. You can’t really be sure h...

  • Page 192

    Determining Other Font Characteristics164Percentage (%)The percentage unit is a relative measurement used to specify the font in relationship to its normal size. Use 50% to make a font half the size it would normally appear and 200% to make it twice the normal size. Use the % symbol to indicate p...

  • Page 193

    Book II Chapter 2Styling TextDetermining Other Font Characteristics165 Figure 2-8: Here are a few of the things you can do to modify text. CSS uses a potentially confusing set of rules for the various font manipulation tools. One rule determines the font style, and another determines boldness.I ...

  • Page 194

    Determining Other Font Characteristics166 Figure 2-9: You can make italic text with the font-style attribute. The font-style values can be italic, normal, or oblique (tilted toward the left).If you want to set a particular segment to be set to italic, normal, or oblique style, use the font-style...

  • Page 195

    Book II Chapter 2Styling TextDetermining Other Font Characteristics167If you want to make some of your text bold, use the font-weight CSS attri-bute, like this:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>bol...

  • Page 196

    Determining Other Font Characteristics168The underline.html code produces a page similar to Figure 2-11. Figure 2-11: You can underline text with text-decoration. You can also use text-decoration for other effects, such as strikethrough (called “line-through” in CSS), as shown in the follow...

  • Page 197

    Book II Chapter 2Styling TextDetermining Other Font Characteristics169 Figure 2-12: Text-decoration can be used for a strike-through effect. ✦ Blink: The blink attribute is a distant cousin of the legendary <blink> tag in Netscape and causes the text to blink on the page. The <blink&...

  • Page 198

    Determining Other Font Characteristics170 Figure 2-13: This text is centered with text-align. You can apply the text-align attribute only to text. The old <center> tag could be used to center nearly anything (a table, some text, or images), which was pretty easy but caused problems. Book ...

  • Page 199

    Book II Chapter 2Styling TextDetermining Other Font Characteristics171 ✦ Line-height: Indicates the vertical spacing between lines in the element. As with letter and word spacing, you’ll probably be disappointed if you’re this concerned about exactly how things are displayed.Using the font ...

  • Page 200

    Determining Other Font Characteristics172The great thing about the font rule is how it combines many of the other font-related rules for a simpler way to handle most text-formatting needs.The font attribute is extremely handy. Essentially, it allows you to roll all the other font attributes into ...

  • Page 201

    Book II Chapter 2Styling TextDetermining Other Font Characteristics173 Figure 2-15: This page has superscripts and subscripts (and, ooooh, math!). Surprisingly, you don’t need CSS to produce superscripts and subscripts. These properties are managed through HTML tags. You can still style them t...

  • Page 202

    174 Book II: Styling with CSSwww.freepdf-books.com

  • Page 203

    Chapter 3: Selectors: Coding with Class and StyleIn This Chapter✓ Modifying specific named elements✓ Adding and modifying emphasis and strong emphasis✓ Creating classes✓ Introducing span and div✓ Using pseudo-classes and the link tag✓ Selecting specific contexts✓ Defining multiple ...

  • Page 204

    Selecting Particular Segments176 Figure 3-1: This page has three kinds of paragraphs. <!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>quote.html</title> <style type = "text/css"> #...

  • Page 205

    Book II Chapter 3Selectors: Coding with Class and StyleUsing Emphasis and Strong Emphasis177Sometimes (as in the Shakespeare insult page), you want to give one element more than one style. You can do this by naming each element and using the name in the CSS style sheet. Here’s how it works: 1. ...

  • Page 206

    Using Emphasis and Strong Emphasis178 Figure 3-2: You can use em and strong to add emphasis. The code for the emphasis.html page is pretty straightforward. It has no CSS at all:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> ...

  • Page 207

    Book II Chapter 3Selectors: Coding with Class and StyleModifying the Display of em and strong179as italic, you’re pretty much stuck with that. The HTML way describes the meaning, and you can define it how you want.Modifying the Display of em and strongFigure 3-3 shows how you might modify the ...

  • Page 208

    Defining Classes180The semantic markups are more useful than the older (more literal) tags because they still tell the truth even if the style has been changed. (In the HTML code, the important thing is whether the text is emphasized, not what it means to emphasize the text. That job belongs to C...

  • Page 209

    Book II Chapter 3Selectors: Coding with Class and StyleDefining Classes181Questions and answers are all paragraphs, so you can’t simply style the paragraph because you need two distinct styles. There’s more than one question and more than one answer, so the ID trick would be problematic. Two ...

  • Page 210

    Defining Classes182Using classesHere’s the code for the classes.html page, showing how to use CSS classes:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>classes.html</title> <style type = "t...

  • Page 211

    Book II Chapter 3Selectors: Coding with Class and StyleDefining Classes183 Figure 3-5: There’s red, there’s script, and then there’s both. The paragraphs in Figure 3-5 appear to be in three different styles, but only red and script are defined. The third paragraph uses both classes. Here...

  • Page 212

    Introducing div and span184The style sheet introduces two classes. The red class makes the paragraph red (well, white text with a red background), and the script class applies a cursive font to the element.The first two paragraphs each have a class, and the classes act as you’d expect. The inte...

  • Page 213

    Book II Chapter 3Selectors: Coding with Class and StyleIntroducing div and span185Organizing the page by meaningTo see why div and span are useful, take a look at Figure 3-6. Figure 3-6: This page has names and phone numbers. The formatting of the page isn’t complete (read about positioning C...

  • Page 214

    Introducing div and span186 <span class = "phone">222-2222</span> </div> <div class = "contact"> <span class = "name">Matthew</span> <span class = "phone">333-3333</span> </div> ...

  • Page 215

    Book II Chapter 3Selectors: Coding with Class and StyleUsing Pseudo-Classes to Style Links187The point is this: After you define the data, you can control it as much as you want. Using span and div to define your data gives you far more control than tables and leaves your HTML code much cleaner.d...

  • Page 216

    Using Pseudo-Classes to Style Links188 Figure 3-8: Links can have three states: normal, visited, and hover. Take a look at the code and see how it’s done:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>linkS...

  • Page 217

    Book II Chapter 3Selectors: Coding with Class and StyleUsing Pseudo-Classes to Style Links189Nothing is special about the links in the HTML part of the code. The links change their state dynamically while the user interacts with the page. The style sheet determines what happens in the various sta...

  • Page 218

    Selecting in Context190Selecting in ContextCSS allows some other nifty selection tricks. Take a look at Figure 3-9 and you see a page with two kinds of paragraphs in it.The code for the context-style.html page is deceptively simple:<!DOCTYPE html><html lang = "en-US"> &l...

  • Page 219

    Book II Chapter 3Selectors: Coding with Class and StyleDefining Styles for Multiple Elements191If you look at the code for context-style.html, you see some interesting things: ✦ The page has two divs. One div is anonymous, and the other is special. ✦ None of the paragraphs has an ID or class....

  • Page 220

    Defining Styles for Multiple Elements192As shown in Figure 3-10, the top three headings all have very similar styles. Creating three different styles would be tedious, so CSS includes a shortcut:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = &quo...

  • Page 221

    Book II Chapter 3Selectors: Coding with Class and StyleUsing New CSS3 Selectors193 You might wonder why we need so many different kinds of selectors. You can use the tag name for most elements, and just apply a class or ID to any element that requires special attention. That’s true, but one goa...

  • Page 222

    Using New CSS3 Selectors194notThere are times you want an inverse selection. For example, imagine you wanted to apply a style to all the paragraphs that are not members of the special class: p:not(.special) { border: 1px solid red; }nth-childThe nth-child selector allows you to select one or...

  • Page 223

    Book II Chapter 3Selectors: Coding with Class and StyleUsing New CSS3 Selectors195 ✦ :nth-of-type(N): This selector works just like nth-child, except it filters to a specific type and ignores any elements that are not of exactly the same type of element. ✦ last-child: This (naturally enough) ...

  • Page 224

    Using New CSS3 Selectors196 ✦ :focus: The :focus pseudo-class is activated when an element is ready to receive keyboard input. ✦ :active: A form element is active when it is currently being used: for example, when a button has been pressed but not yet released. Mobile devices often skip direc...

  • Page 225

    Chapter 4: Borders and BackgroundsIn This Chapter✓ Creating borders✓ Managing border size, style, and color✓ Using the border shortcut style✓ Understanding the box model✓ Setting padding and margin✓ Creating background and low-contrast images✓ Changing background image settings✓ A...

  • Page 226

    Joining the Border Patrol198The code for the borderProps.html page demonstrates the basic principles of borders in CSS:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>borderProps.html</title> <styl...

  • Page 227

    Book II Chapter 4Styling with CSSJoining the Border Patrol199 You must define all three attributes if you want borders to appear properly. You can’t rely on the default values to work in all browsers.Defining border stylesCSS has a predetermined list of border styles you can choose from. Figure...

  • Page 228

    Joining the Border Patrol200Using the border shortcutDefining three different CSS attributes for each border is a bit tedious. Fortunately, CSS includes a handy border shortcut that makes borders a lot easier to define, as Figure 4-3 demonstrates. Figure 4-3: This border is defined with only on...

  • Page 229

    Book II Chapter 4Styling with CSSJoining the Border Patrol201<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>borderShortcut.html</title> <style type = "text/css"> h1 { borde...

  • Page 230

    Introducing the Box Model202<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>subBorders.html</title> <style type = "text/css"> h1 { border-bottom: 5px black double; } ...

  • Page 231

    Book II Chapter 4Styling with CSSIntroducing the Box Model203Your overall page is defined in block-level elements, which contain inline ele-ments for detail.Each block-level element (at least in the default setting) takes up the entire width of the parent element. The next block-level element goe...

  • Page 232

    Introducing the Box Model204You can change settings for the margin, border, and padding to adjust the space around your elements. The margin and padding CSS rules are used to set the sizes of these elements, as shown in Figure 4-6. Figure 4-6: Margins and padding affect the positioning of an el...

  • Page 233

    Book II Chapter 4Styling with CSSIntroducing the Box Model205 </head> <body> <h1>Margins and padding</h1> <div id = "main"> <p>This paragraph has the default margins and padding</p> <p id = "margin">This paragra...

  • Page 234

    Introducing the Box Model206 ✦ You can adjust the width of a block. The main div that contains all the paragraphs has its width set to 75 percent of the page body width. ✦ Center an element by setting margin-left and margin-right to auto. Set both the left and right margins to auto to make an...

  • Page 235

    Book II Chapter 4Styling with CSSNew CSS3 Border Techniques207New CSS3 Border TechniquesBorders have been a part of CSS from the beginning, but CSS3 adds some really exciting new options. Modern browsers now support borders made from an image as well as rounded corners and box shadows. These t...

  • Page 236

    New CSS3 Border Techniques208 h2 { border-width: 15px; border-image: url("frame.png") 25% repeat; -webkit-border-image: url("frame.png") 25% repeat; -moz-border-image: url("frame.png") 25% repeat; }Here’s how you add a border image: 1. Acquire your im...

  • Page 237

    Book II Chapter 4Styling with CSSNew CSS3 Border Techniques209Figure 4-9 shows the image being used as a border around my headline. Figure 4-9: Using an image as a custom border. Adding Rounded CornersOlder CSS was known for being very rectangular, so web designers tried to soften their designs...

  • Page 238

    New CSS3 Border Techniques210It’s pretty easy to get rounded corners on those browsers that support the tag:<!DOCTYPE HTML><html lang = "en"> <head> <title>corners.html</title> <meta charset = "UTF-8" /> <style type = "text/css...

  • Page 239

    Book II Chapter 4Styling with CSSNew CSS3 Border Techniques211 .shadow { box-shadow: 10px 10px 10px #000000; height: 200px; width: 200px; padding: 1em; border: 1px solid black; border-radius: 5px; background-color: #EEEEEE; } </style></head&...

  • Page 240

    Changing the Background Image212 3. Specify the offset. A shadow is typically offset from the rectangle it belongs to. The first two values indicate the horizontal and vertical offset. Measure using any of the standard CSS measurements (normally pixels or ems). 4. Determine the blur and spread d...

  • Page 241

    Book II Chapter 4Styling with CSSChanging the Background Image213Background images are easy to apply. The code for backgroundImage.html shows how:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>backgroundImage...

  • Page 242

    Changing the Background Image214 5. Test your background image by viewing the web page in your browser. A lot can go wrong with background images. The image may not be in the right directory, you might have misspelled its name, or you may have forgotten the url() bit. (I do all those things some...

  • Page 243

    Book II Chapter 4Styling with CSSChanging the Background Image215Solutions to the background conundrumWeb developers have come up with a number of solutions to background image issues over the years. I used several of these solutions in the backgroundImage.html page (the readable one shown in Fi...

  • Page 244

    Changing the Background Image216Getting a tiled imageIf you want an image that repeats seamlessly, you have two main options: ✦ Find an image online. A number of sites online have free seamless back-grounds for you to use on your site. Try a search and see what you come up with. ✦ Make your o...

  • Page 245

    Book II Chapter 4Styling with CSSChanging the Background Image217Reducing the contrastIn backgroundImage.html, the heading text is pretty dark, which won’t show up well against the dark background image. I used a different trick for the h1 heading. The heading uses a different version of the ro...

  • Page 246

    Manipulating Background Images218background color appears immediately because it is defined in CSS. This is especially important for light text because white text on the default white background is invisible. After the background image appears, it overrides the background color. Be sure the text ...

  • Page 247

    Book II Chapter 4Styling with CSSManipulating Background Images219 <meta charset = "UTF-8"> <title>noRepeat.html</title> <style type = "text/css"> body { background-image: url("ropeBG.jpg"); background-repeat: no-re...

  • Page 248

    Manipulating Background Images220Now it looks like everybody’s settling on the Mozilla-style implementation, which is pretty easy to use and the one demonstrated here. If you search on the web, you will see some other syntaxes, especially for WebKit-based browsers, but the mechanism described h...

  • Page 249

    Book II Chapter 4Styling with CSSManipulating Background Images221 3. Invoke the linear-gradient function. A few CSS elements such as url() and rgba() require parentheses because technically they are functions. The distinction doesn’t matter right now, but you need to incorporate the parenthes...

  • Page 250

    Manipulating Background Images222 1. Use an angle for direction. Rather than specifying your gradient direction with the standard top/ left keywords, you can specify a starting angle. Angles are measured mathematically in degrees, with 0 coming from the right and 90 coming from top-down. You mus...

  • Page 251

    Book II Chapter 4Styling with CSSUsing Images in Lists223Radial gradients have many options, which makes them quite promising, but the browser support for these various standards is quite spotty. Box 4 has a radial gradient with three colors:#box4 { background-image: radial-gradient(red, ...

  • Page 252

    Using Images in Lists224<!DOCTYPE html> <html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>listImages.html</title> <style type = "text/css"> li { list-style-image: url("pepper.gif"); ...

  • Page 253

    Chapter 5: Levels of CSSIn This Chapter✓ Building element-level styles✓ Creating external style sheets✓ Creating a multipage style✓ Managing cascading styles✓ Working with a CSS reset style✓ Using conditional commentsC SS is a great tool for setting up the visual display of your pages...

  • Page 254

    Managing Levels of Style226 Figure 5-1: This page has styles, but they’re defined in a new way. <!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>localStyles.html</title> </head> <body> ...

  • Page 255

    Book II Chapter 5Levels of CSSManaging Levels of Style227When to use local stylesLocal styles should not be your first choice, but they can be useful in some circumstances.If you’re writing a program to translate from a word processor or other tool, local styles are often the easiest way to mak...

  • Page 256

    Managing Levels of Style228 ✦ Readability: If style information is interspersed throughout the page, it’s much more difficult to find and modify than if it’s centrally located in the header (or in an external document, as you’ll see shortly). ✦ Lack of separation: Placing the styles at ...

  • Page 257

    Book II Chapter 5Levels of CSSManaging Levels of Style229When you look at the code for externalStyle.html, you might be surprised to see no obvious style information at all!<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> &...

  • Page 258

    Managing Levels of Style230The style sheet looks just like a page-level style, except for a few key differences: ✦ The style sheet rules are contained in a separate file. The style is no longer part of the HTML page but is an entirely separate file stored on the server. CSS files usually end w...

  • Page 259

    Book II Chapter 5Levels of CSSManaging Levels of Style231The code shows how easily this is done:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>SecondPage.html</title> <link rel = "stylesheet&q...

  • Page 260

    Managing Levels of Style232 ✦ The tag has no visual presence. The user can’t see the <link> tag, only its effects. ✦ The <link> tag is used to relate the document with another docu-ment. You use the <link> tag to describe the relationship between documents. ✦ The <lin...

  • Page 261

    Book II Chapter 5Levels of CSSUnderstanding the Cascading Part of Cascading Style Sheets 233Understanding the Cascading Part of Cascading Style SheetsThe C in CSS stands for cascading, which is an elegant term for an equally elegant and important idea. Styles cascade or flow among levels. An ele...

  • Page 262

    Understanding the Cascading Part of Cascading Style Sheets 234 p { font-family: comic sans ms, fantasy; } .italicized { font-style: italic; } #bold { font-weight: bold; } </style> </head> <body> <h1>Cascading Style...

  • Page 263

    Book II Chapter 5Levels of CSSUnderstanding the Cascading Part of Cascading Style Sheets 235element in the body begins with the style of the page. This makes it easy to define an overall page style. ✦ A block-level element passes its style to its children. If you define a div with a particular ...

  • Page 264

    Understanding the Cascading Part of Cascading Style Sheets 236The question is this: What color will the whatColor element display? It’s a member of the body, so it should be red. It’s also a paragraph, and paragraphs are green. It’s also a member of the myClass class, so it should be blue. ...

  • Page 265

    Book II Chapter 5Levels of CSSManaging Browser Incompatibility237external style has the weakest rank. You can write a page-level style rule to override an external style.You might do this if you decide all your paragraphs will be blue, but you have one page where you want the paragraphs green. De...

  • Page 266

    Managing Browser Incompatibility238 ✦ Parallel pages: You might be tempted to create two versions of your page, one for IE and one for the standards-compliant browsers (Firefox, Netscape Navigator, Opera, Safari, and so on). This is also a bad solution because it’s twice (or more) as much wor...

  • Page 267

    Book II Chapter 5Levels of CSSManaging Browser Incompatibility239 Figure 5-6: And this is IE. Somehow the code knows the difference. Take a look at the code for IEorNot.html and see how it works.<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = &quo...

  • Page 268

    Managing Browser Incompatibility240conditional comment but sees an HTML comment (which begins with <!-- and ends with --> ). HTML comments are ignored, so the browser does nothing.Using a conditional comment with CSSConditional comments on their own aren’t that interesting, but they can b...

  • Page 269

    Book II Chapter 5Levels of CSSManaging Browser Incompatibility241If the page is rendered in IE, it uses a second style sheet.Look at the code, and you’ll see it’s very similar to the IEorNot.html page.<!DOCTYPE html><html lang = "en-US"> <head> <meta chars...

  • Page 270

    Managing Browser Incompatibility242 <!--[if IE]> <![endif]--> 3. Build a new IE-specific style inside the comment. The style inside the comment will be applied only to IE browsers, such as in the following lines: <!--[if IE]> <style type = "text/css"...

  • Page 271

    Book II Chapter 5Levels of CSSManaging Browser Incompatibility243Using a CSS resetEven when browsers agree on which CSS elements to incorporate, they some-times differ on the actual details. For example, they may choose different margins and paddings for list elements. Web developers often use a ...

  • Page 272

    244 Book II: Styling with CSSwww.freepdf-books.com

  • Page 273

    Chapter 6: CSS Special EffectsIn This Chapter✓ Adding reflections✓ Working with opacity✓ Manipulating text with strokes and shadows✓ Adding transformations to elements✓ Animating with transitionsC SS is great for adding visual interest to websites. Newer implementa-tions of CSS go even ...

  • Page 274

    Image Effects246 Figure 6-1: The box and text are partially transparent. The complete code for this page is easy to follow:<!DOCTYPE HTML><html lang = "en"> <head> <title>opacity.html</title> <meta charset = "UTF-8" /> <style t...

  • Page 275

    Book II Chapter 6CSS Special EffectsImage Effects247All of the code is common HTML and CSS2 stuff, except the last attribute. The opacity attribute takes a single floating point value between 0 and 1. Zero (0) is completely transparent and one (1) is completely opaque.Note that Figure 6-1 also i...

  • Page 276

    Image Effects248Apply the following CSS to make any element with the reflect class have a nice-looking reflection in the supported browsers:-webkit-box-reflect: below 2px; Basic reflections are quite simple: 1. Apply the -webkit-box-reflect attribute. Unfortunately, there is no generic version, ...

  • Page 277

    Book II Chapter 6CSS Special EffectsText Effects249completely opaque. (Of course, you can use rgba() to set any other transparency value you want, but only the alpha part is important in this context.) 4. Finish at complete opacity. The top of the original image (the bottom of the reflection) sh...

  • Page 278

    Text Effects250Figure 6-3 shows a page with stroked text. Figure 6-3: You can add an outline to text for interesting effects. The text-stroke rule applies this effect. You can see it used in the code:<!DOCTYPE HTML><html lang = "en"> <head> <title>textStrok...

  • Page 279

    Book II Chapter 6CSS Special EffectsText Effects251Text-shadowShadows are another common feature of modern web designs. Shadows add an element of depth to a page, but they can also enhance readability (if used properly) to lift a headline from the page. The text-shadow attribute was technically p...

  • Page 280

    Transformations and Transitions252The text-shadow attribute has four parameters: ✦ offset-x: Determines how far in the x (left-right) axis the shadow will be from the original text. A positive value moves the shadow to the right, and a negative value moves to the left. ✦ offset-y: Determines ...

  • Page 281

    Book II Chapter 6CSS Special EffectsTransformations and Transitions253TransformationsCSS3 includes the ability to apply geometric transformations onto any ele-ment. This provides a remarkable level of visual control not previously avail-able to web developers.The transform attribute allows you to...

  • Page 282

    Transformations and Transitions254This code is illustrated in Figure 6-5. Figure 6-5: Page elements can be transformed. Note that browser support is changing on this element. Chrome and Safari still expect the -webkit prefix, but Firefox and Opera support the non-prefixed version. IE 10 theoret...

  • Page 283

    Book II Chapter 6CSS Special EffectsTransformations and Transitions255Ordinary, 2D animations utilize the 2D coordinate system, with an X axis going side-to-side and a Y axis traversing top-to-bottom. Even in 2D transformations, there is a tacit acknowledgment of a Z axis. The Z axis goes through...

  • Page 284

    Transformations and Transitions256 ✦ Box 4 is upside-down: I rotated box 4 180 degrees around the X axis, flipping it completely. Note that rotating around the Y axis would also flip the box, but the text would remain at the top, and would be reversed along the vertical axis. ✦ Box 5 is doing...

  • Page 285

    Book II Chapter 6CSS Special EffectsTransformations and Transitions257 <div id = "box1">box 4</div> <div id = "box1">box 5</div> </body></html>The first new rule is perspective. Change the perspective of the parent element that will contain ...

  • Page 286

    Transformations and Transitions258 Figure 6-7: As you hover over elements, they change! Look at a simple h1 heading: <h1>Transition Demo</h1>The CSS code is mainly quite straightforward: h1 { color: black font-size: 300%; transition:color 1s ease-in; } h1:hover { color: r...

  • Page 287

    Book II Chapter 6CSS Special EffectsTransformations and Transitions259 #box { transition: all 1s ease-in; height: 100px; width: 100px; border: 1px solid black; } #box:hover { transform: rotate(180deg); } The transform is defined in the: hover pseudo-class. The only new ele-ment is ...

  • Page 288

    Transformations and Transitions260 Figure 6-8: The box auto- matically moves as indicated by the arrows. Here’s the basic strategy for building a CSS animation: 1. Generate a set of keyframes. Animations are based on the notion of keyframes. Each keyframe speci-fies the state of an object, an...

  • Page 289

    Book II Chapter 6CSS Special EffectsTransformations and Transitions261Take a look at the code for animation.html to see it all in action:<!doctype html><html lang="en"> <head> <meta charset="UTF-8"> <title>animation.html</title> <st...

  • Page 290

    Transformations and Transitions262the animation at a constant speed. You can also use ease-in-out (the default behavior) to make the element move at a variable rate. ✦ Determine the number of repetitions: You can specify a number of times to repeat the animation. If you leave this part out, the...

  • Page 291

    actionURI(http://www.dummies.com/extras/html5css3aio):Visit actionURI(http://www.dummies.com/extras/html5css3aio):www.dummies.com/extras/html5css3aioactionURI(http://www.dummies.com/extras/html5css3aio): for more on resetting and extending CSS.Part IIIBuilding Layouts with CSSwww.freepdf-books.com

  • Page 292

    Contents at a Glance Contents at a GlanceChapter 1: Fun with the Fabulous Float . . . . . . . . . . . . . . . . . . . . . . . . .265Avoiding Old-School Layout Pitfalls ..............................................................................265Introducing the Floating Layout Mechanism ........

  • Page 293

    Chapter 1: Fun with the Fabulous FloatIn This Chapter✓ Understanding the pitfalls of traditional layout tools✓ Using float with images and block-level tags✓ Setting the width and margins of floated elements✓ Creating attractive forms with float✓ Using the clear attribute with floatO ne ...

  • Page 294

    Avoiding Old-School Layout Pitfalls266 ✦ Complexity: If you had a master page with four segments, you had to keep track of five web pages. A master page kept track of the relative positions of each section, but had no content of its own. Each of the other pages had content but no built-in aware...

  • Page 295

    Book III Chapter 1Fun with the Fabulous FloatAvoiding Old-School Layout Pitfalls267you probably won’t use an ordinary table but tricks, like rowspan and colspan, special spacer images, and tables inside tables. It doesn’t take long for the code to become bulky and confusing. ✦ Content and d...

  • Page 296

    Introducing the Floating Layout Mechanism268development (especially for embedded games — check out my earlier book, Beginning Flash Game Programming For Dummies, published by John Wiley & Sons). Even though Flash has historic significance, you should avoid using it for ordinary web developm...

  • Page 297

    Book III Chapter 1Fun with the Fabulous FloatIntroducing the Floating Layout Mechanism269In a floating layout, you don’t legislate exactly where everything will go. Instead, you provide hints and let the browser manage things for you. This ensures flexibility because the browser will try to fol...

  • Page 298

    Introducing the Floating Layout Mechanism270 Figure 1-2: Now the text wraps around the image. Adding the float propertyThe code for adding the float property is pretty simple:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> ...

  • Page 299

    Book III Chapter 1Fun with the Fabulous FloatUsing Float with Block-Level Elements271 Figure 1-3: Now the image is floated to the right. The only new element in the code is the CSS float attribute. The img object has a float:left attribute. It isn’t necessary to change any other attri-butes of...

  • Page 300

    Using Float with Block-Level Elements272 Figure 1-4: Paragraphs 2 and 3 are acting strangely. As you can see, some strange formatting is going on here. I improve on things later to make the beginnings of a two-column layout, but for now, just take a look at what’s going on: ✦ I’ve added bo...

  • Page 301

    Book III Chapter 1Fun with the Fabulous FloatUsing Float with Block-Level Elements273The code to produce this is simple HTML with equally simple CSS markup:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>floatD...

  • Page 302

    Using Float with Block-Level Elements274 The exception to this rule is elements with a predefined width, such as images and many form elements. These elements already have an implicit width, so you don’t need to define width in the CSS. If in doubt, try setting the width at various values until...

  • Page 303

    Book III Chapter 1Fun with the Fabulous FloatUsing Float with Block-Level Elements275 When you use a percentage value in the context of width, you’re expressing a percentage of the parent element (in this case, the body because the para-graph is embedded in the document body). Setting the width...

  • Page 304

    Using Float to Style Forms276<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>floatWidthMargin.html</title> <style type = "text/css"> p { border: 2px black solid; } ...

  • Page 305

    Book III Chapter 1Fun with the Fabulous FloatUsing Float to Style Forms277intent of the page, and the CSS can be modified separately. Using external CSS is a natural extension of this philosophy. Begin by looking at floatForm.html and concentrate on the HTML structure before worrying about style:...

  • Page 306

    Using Float to Style Forms278 ✦ The CSS is external. CSS is defined in an external document. This makes it easy to change the style and helps you to focus on the HTML docu-ment in isolation. ✦ The HTML code is minimal. The code is very clean. It includes a form with a fieldset. The fieldset c...

  • Page 307

    Book III Chapter 1Fun with the Fabulous FloatUsing Float to Style Forms279 If you have a page with styles and you want to see how it will look without the style rules, use Chrome developer tools or Firebug. You can temporarily disable some or all CSS style rules to see the default content underne...

  • Page 308

    Using Float to Style Forms280 3. Set the label width to 5em. This gives you plenty of space for the text the labels will contain. 4. Set the labels to be right-aligned. Right-aligning the labels makes the text snug up to the input elements but gives them a little margin-right so the text isn’...

  • Page 309

    Book III Chapter 1Fun with the Fabulous FloatUsing Float to Style Forms281 Figure 1-10: The form looks great when the page is skinny. Things get worse when the page is a little wider, as you can see in Figure 1-11. Figure 1-11: With a slightly wider browser, things get strange. If you make the...

  • Page 310

    Using Float to Style Forms282 Figure 1-12: The browser is trying to put all the inputs on the same line. When CSS doesn’t do what you want, it’s usually acting on some false assumptions, which is the case here. Floating left causes an element to go as far to the left as possible and on the n...

  • Page 311

    Book III Chapter 1Fun with the Fabulous FloatUsing Float to Style Forms283 Figure 1-13: With a narrower fieldset, all the elements look much nicer. Unfortunately, this doesn’t always work because the user may adjust the font size and mess up all your careful design.Using the clear attribute to...

  • Page 312

    Using Float to Style Forms284 Figure 1-14: When you apply clear to floating elements, you can control the layout. Here’s the final CSS code, including clear attributes in the labels and button:/* floatForm.css CSS file to go with float form Demonstrates use of float, width, margin, and cle...

  • Page 313

    Chapter 2: Building Floating Page LayoutsIn This Chapter✓ Creating a classic two-column page✓ Creating a page-design diagram✓ Using temporary background colors✓ Creating fluid layouts and three-column layouts✓ Working with and centering fixed-width layoutsT he floating layout technique ...

  • Page 314

    Creating a Basic Two-Column Design286 ✦ Color scheme: What are the main colors of your site? What will be the color and background color of each section?This particular sketch (in Figure 2-1) is very simple because the page will use default colors and fonts. For a more complex job, you need a ...

  • Page 315

    Book III Chapter 2Building Floating Page LayoutsCreating a Basic Two-Column Design287Building the HTMLAfter you have a basic design in place, you’re ready to start building the HTML code that will be the framework. Start with basic CSS, but create a div for each section that will be in your fin...

  • Page 316

    Creating a Basic Two-Column Design288 Figure 2-2: The plain HTML is plain indeed; some CSS will come in handy. Using temporary background colorsAnd now for one of my favorite CSS tricks… Before doing anything else, create a selector for each of the named divs and add a temporary back-ground co...

  • Page 317

    Book III Chapter 2Building Floating Page LayoutsCreating a Basic Two-Column Design289#left { background-color: yellow;} #right { background-color: green;} #footer { background-color: orange;}You won’t keep these background colors, but they provide some very useful cues while you’re working...

  • Page 318

    Creating a Basic Two-Column Design290 It’s fine that you can’t see the actual colors in the black-and-white image in Figure 2-3. Just appreciate that when you see the page in its full-color splen-dor, the various colors will help you see what’s going on.Setting up the floating columnsThis ...

  • Page 319

    Book III Chapter 2Building Floating Page LayoutsCreating a Basic Two-Column Design291 Figure 2-4: Now, the left column is floated. Tuning up the bordersThe colored backgrounds in Figure 2-4 point out some important features of this layout scheme. For instance, the two columns are not the same h...

  • Page 320

    Creating a Basic Two-Column Design292The final effect is shown in Figure 2-5. Figure 2-5: This is a decent design, which adjusts with the page width. Advantages of a fluid layoutThis type of layout scheme (with floats and variable widths) is often called a fluid layout because it has columns bu...

  • Page 321

    Book III Chapter 2Building Floating Page LayoutsCreating a Basic Two-Column Design293 <title>semantic</title> <meta charset="UTF-8"> <style type = "text/css"> header { border-bottom: 5px double black; } nav { float: left; width: 20%; ...

  • Page 322

    Creating a Basic Two-Column Design294 <article> <h2>Article</h2> <p>Article body...</p> </article> <footer> <h2>Footer</h2> <address> Andy Harris <br /> <a href = "mailto:andy@aharrisbooks.net"...

  • Page 323

    Book III Chapter 2Building Floating Page LayoutsBuilding a Three-Column Design295HTML5 introduced a number of other seman-tic tags. Most of them have no specific for-matting. Still, you will run across them, so here are a few that seem likely to make the cut: ✓ address: Holds contact informati...

  • Page 324

    Building a Three-Column Design296This design uses very basic CSS with five named divs. Here’s the code (with the dummy paragraph text removed for space):<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>threeCo...

  • Page 325

    Book III Chapter 2Building Floating Page LayoutsBuilding a Three-Column Design297 width: 60%; padding-left: 1%;} #right { float: left; width: 17%; padding-left: 1%;} #footer { border: 1px black solid; float: left; width: 100%; clear: both; text-align: center;}Each element (except the he...

  • Page 326

    Building a Three-Column Design298adjustments come later, but you certainly don’t want to take up more than 100 percent of the available real estate. 9. Float and clear the footer. To get the footer acting right, you need to float it and clear it on both margins. Set its width to 100 percent, i...

  • Page 327

    Book III Chapter 2Building Floating Page LayoutsBuilding a Three-Column Design299Figure 2-7 shows an important aspect of this type of layout. The columns are actually blocks, and each is a different height. Typically, I think of a column as stretching the entire height of a page, but this isn’...

  • Page 328

    Building a Three-Column Design300 width: 60%; padding-left: 1%; padding-right: 1%; min-height: 30em;} #right { float: left; width: 17%; padding-left: 1%; min-height: 30em; background-color: #EEEEEE;} #footer { border: 1px black solid; float: left; width: 100%; clear: both; text-alig...

  • Page 329

    Book III Chapter 2Building Floating Page LayoutsBuilding a Three-Column Design301 Figure 2-9: The page is too small to hold the text. Note the scroll bar. If you set the height and width to a specific percentage of the page width, there is a danger the text will not fit. You can resolve this by ...

  • Page 330

    Building a Fixed-Width Layout302#footer { border: 1px black solid; float: left; width: 100%; clear: both; text-align: center;} Setting the overflow property tells the browser what to do if it cannot place the text in the indicated space. Use overflow: auto to place scrollbars only when neces...

  • Page 331

    Book III Chapter 2Building Floating Page LayoutsBuilding a Fixed-Width Layout303Setting up the HTMLAs usual, the HTML code is minimal. It contains a few named divs. (Like usual, I’ve removed filler text for space reasons.)<!DOCTYPE html><html lang = "en-US"> <head>...

  • Page 332

    Building a Fixed-Width Layout304 height: 30em; overflow: auto; padding-left: .5em;} #footer { width: 800px; text-align: center; background-color: #e2e393; border-top: 3px double black; clear: both;}It’s all pretty straightforward: 1. Color each element to see what’s happening. Begin ...

  • Page 333

    Book III Chapter 2Building Floating Page LayoutsBuilding a Centered Fixed-Width Layout305 9. Adjust widths again. Adding borders, padding, and margin can change the widths of the exist-ing elements. After you’ve modified these attributes, take a careful look at your layout to be sure it didn...

  • Page 334

    Building a Centered Fixed-Width Layout306Making a surrogate body with an all divIn any case, the HTML requires only one new element, an all div that encases everything else inside the body (as usual, I removed the placeholder text):<!DOCTYPE html><html lang = "en-US"> <...

  • Page 335

    Book III Chapter 2Building Floating Page LayoutsBuilding a Centered Fixed-Width Layout307#left { float: left; width: 200px; clear: left; border-right: 1px solid black; height: 400px; padding-right: .5em;} #right { float: left; width: 580px; height: 400px; padding-left: .5em;} #footer { ...

  • Page 336

    Building a Centered Fixed-Width Layout308Limitations of the jello layoutJello layouts represent a compromise between fixed and fluid layouts, but they aren’t perfect: ✦ Implicit minimum width: Very narrow browsers (like cellphones) can’t render the layout the way you want. Fortunately, the ...

  • Page 337

    Chapter 3: Styling Lists and MenusIn This Chapter✓ Using CSS styles with lists✓ Building buttons from lists of links✓ Dynamically displaying sublists✓ Managing vertical and horizontal lists✓ Building CSS-based menusM ost pages consist of content and navigation tools. Almost all pages h...

  • Page 338

    Revisiting List Styles310Defining navigation as a list of linksIf you look at the HTML, you’ll be astonished at its simplicity:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>buttonList.html</title> ...

  • Page 339

    Revisiting List Styles311Book III Chapter 3Styling Lists and Menus text-align: center; margin-left: -2.5em;} #menu a { text-decoration: none; color: black; display: block; background-color: #EEEEFF; box-shadow: 5px 5px 5px gray; margin-bottom: 2px;} #menu a:hover { background-color: #DD...

  • Page 340

    Revisiting List Styles312 4. Specify the width of each button: width: 5em; A group of buttons looks best if they’re all the same size. Use the CSS width attribute to set each li to 5em. 5. Remove the margin by using a negative margin-left value, as shown here: margin-left: -2.5em; Lists hav...

  • Page 341

    Revisiting List Styles313Book III Chapter 3Styling Lists and Menus 12. Make the button depress when the mouse hovers on an anchor:#menu a:hover { background-color: #DDDDEE; box-shadow: 3px 3px 3px gray; border: none;} When the mouse hovers on the button, the shadow is smaller, and the backgr...

  • Page 342

    Creating Dynamic Lists314#menu ul { margin-left: -2.5em; } #menu li { list-style-type: none; width: 7em; text-align: center; float: left;} #menu a { text-decoration: none; color: black; display: block; background-color: #EEEEFF; box-shadow: 5px 5px 5px gray; margin-bottom: 2px; margin...

  • Page 343

    Creating Dynamic Lists315Book III Chapter 3Styling Lists and MenusWhen you think of a complex hierarchical organization (which is how most multipage websites end up), the easiest way to describe the structure is in a set of nested lists. HTML lists can contain other lists, and this can be a grea...

  • Page 344

    Creating Dynamic Lists316HTML structure that may go unnoticed in a plain HTML document can cause all kinds of strange problems in your CSS.Here is the code for the nested list in plain HTML:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-...

  • Page 345

    Creating Dynamic Lists317Book III Chapter 3Styling Lists and MenusHiding the inner listsThe first step of creating a dynamic menu system is to hide any lists that are embedded in a list item. Add the following CSS style to your page:li ul { display: none;} In reality, you usually apply this tec...

  • Page 346

    Creating Dynamic Lists318Getting the inner lists to appear on cueThe fun part is getting the interior lists to pop up when the mouse is over the parent element. A second CSS style can make this happen:li ul { display: none;} li:hover ul { display: block;}The new code is pretty interesting. When...

  • Page 347

    Creating Dynamic Lists319Book III Chapter 3Styling Lists and Menus ✦ Display the list as a block. display:block overrides the previous display:none instruction and displays the particular element as a block. The text reappears magically.This hide-and-seek trick isn’t all that great on its ow...

  • Page 348

    Creating Dynamic Lists320not a grandchild or great-grandchild. With this indicator in place, the page acts correctly, as shown in Figure 3-7. Figure 3-7: Now, only the next menu level shows up on a mouse hover. This trick allows you to create nested lists as deeply as you wish and to open any s...

  • Page 349

    Building a Basic Menu System321Book III Chapter 3Styling Lists and Menus I’m not suggesting that this type of menu is a good idea. Having stuff pop around like this is actually pretty distracting. With a little more formatting, you can use these ideas to make a functional menu system. I’m ju...

  • Page 350

    Building a Basic Menu System322Building a vertical menu with CSSThe vertical menu system works with exactly the same HTML as the hid-denList example — only the CSS changed. Here’s the new CSS file:/* vertMenu.css *//* unindent entire list */#menu ul { margin-left: -2.5em;} /* set li as butto...

  • Page 351

    Building a Basic Menu System323Book III Chapter 3Styling Lists and Menus/* show submenus on hover */#menu li:hover > ul { display: block; margin-left: -2em;}Of course, the CSS uses a few tricks, but there’s really nothing new. It’s just a combination of techniques you already know: 1. U...

  • Page 352

    Building a Basic Menu System324 Because the anchors no longer look like anchors, you have to do some-thing else to indicate there’s something special about these elements. When the user moves the mouse over any anchor tag in the menu div, that anchor’s background color will switch to white. ...

  • Page 353

    Building a Basic Menu System325Book III Chapter 3Styling Lists and Menus Figure 3-12: For the multilevel menus, a little bit of indentation is helpful. Again, the HTML is identical. The CSS for a horizontal menu is surprisingly close to the vertical menu. The primary difference is floating the ...

  • Page 354

    Building a Basic Menu System326 /* display sublists on hover */#menu li:hover > ul { display: block;} /* indent third-generation lists */#menu li li li{ margin-left: 1em;}The CSS code has just a few variations from the vertical menu CSS: ✦ Float each list item by adding float and width att...

  • Page 355

    Chapter 4: Using Alternative PositioningIn This Chapter✓ Setting position to absolute✓ Managing z-index✓ Creating fixed and flexible layouts✓ Working with fixed and relative positioning✓ Using the new flexbox modelF loating layouts (described in Chapter 2 of this minibook) are the prefe...

  • Page 356

    Working with Absolute Positioning328 <title>boxes.html</title> <style type = "text/css"> #blueBox { background-color: blue; width: 100px; height: 100px; } #blackBox { background-color: black; width: 100px; ...

  • Page 357

    Book III Chapter 4 Using Alternative PositioningWorking with Absolute Positioning329 <!DOCTYPE html> <html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>absPosition.html</title> <style type = "text/css"&...

  • Page 358

    Working with Absolute Positioning330Making absolute positioning workA few new parts of CSS allow this more direct control of the size and position of these elements. Here’s the CSS for one of the boxes: #blueBox { background-color: blue; width: 100px; height: 100px; ...

  • Page 359

    Book III Chapter 4 Using Alternative PositioningManaging z-index331Managing z-indexWhen you use absolute positioning, you can determine exactly where things are placed, so it’s possible for them to overlap. By default, elements described later in HTML are positioned on top of elements described...

  • Page 360

    Building a Page Layout with Absolute Positioning332 left: 0px; top: 0px; margin: 0px; z-index: 1; } #blackBox { background-color: black; width: 100px; height: 100px; position: absolute; left: 50px; top: 50px;...

  • Page 361

    Book III Chapter 4 Using Alternative PositioningBuilding a Page Layout with Absolute Positioning333 Figure 4-4: This layout was created with absolute positioning. The technique for creating an absolutely positioned layout is similar to the floating technique (in the general sense).Overview of ab...

  • Page 362

    Building a Page Layout with Absolute Positioning334 5. Identify each element. It’s easier to see what’s going on if you assign a different colored border to each element. 6. Make each element absolutely positioned. Set position: absolute in the CSS for each element in the layout. 7. Specify...

  • Page 363

    Book III Chapter 4 Using Alternative PositioningBuilding a Page Layout with Absolute Positioning335The HTML file calls an external style sheet called absLayout.css.Adding the CSSThe CSS code is a bit lengthy but not too difficult:/* absLayout.css */#all { border: 1px solid black; width: 800px;...

  • Page 364

    Creating a More Flexible Layout336 ✦ You should specify size and position. With a floating layout, you’re still encouraging a certain amount of fluidity. Absolute positioning means you’re taking the responsibility for both the shape and size of each ele-ment in the layout. ✦ Absolute posi...

  • Page 365

    Book III Chapter 4 Using Alternative PositioningCreating a More Flexible Layout337 Figure 4-6: The layout resizes in proportion to the browser window. The page simply takes up a fixed percentage of the browser screen. The pro-portions are all maintained, no matter what the screen size is. Having...

  • Page 366

    Creating a More Flexible Layout338 #head { border: 1px black solid; position: absolute; left: 0%; top: 0%; width: 100%; height: 10%; text-align: center; } #head h1 { margin-top: 1%; } #menu { border: 1px green solid; position: absolute; left: 0%; top: 10%; width:...

  • Page 367

    Book III Chapter 4 Using Alternative PositioningCreating a More Flexible Layout339Building the layoutHere’s how the layout works: 1. Create an all container by building a div with the all ID. The all container will hold all the contents of the page. It isn’t abso-lutely necessary in this typ...

  • Page 368

    Exploring Other Types of Positioning340Exploring Other Types of PositioningIf you use the position attribute, you’re most likely to use absolute. However, here are other positioning techniques that can be handy in certain circumstances: ✦ Relative: Set position: relative when you want to move...

  • Page 369

    Book III Chapter 4 Using Alternative PositioningExploring Other Types of Positioning341 Figure 4-9: The page scrolls to the Gamma content, but the menu stays put. Normally, when you scroll down the page, things on the top of the page (like the menu) disappear. In this case, the menu stays on the...

  • Page 370

    Exploring Other Types of Positioning342 </div> <div class = "content" id = "alpha"> <h2>Alpha</h2> </div> <div class = "content" id = "beta"> <h2>Beta</h2> </div...

  • Page 371

    Book III Chapter 4 Using Alternative PositioningExploring Other Types of Positioning343h1 { text-align: center; }#menu { position: fixed; width: 18%;}#menu li { list-style-type: none; margin-left: -2em; text-align: center; }#menu a{ display: block; border: 2px gray outset; text-decor...

  • Page 372

    Flexible Box Layout Model344menu. In this example, I set the menu width to 18 percent of the page width (20 percent minus some margin space). 3. Consider the menu position by explicitly setting the top and left attributes. When you specify a fixed position, you can determine where the element is...

  • Page 373

    Book III Chapter 4 Using Alternative PositioningFlexible Box Layout Model345tion would allow any kind of placement through CSS, even after the HTML is finished.Absolute positioning seems great at first, but it has its own problems: ✦ It’s a lot more detail-oriented: Absolute positioning is a ...

  • Page 374

    Flexible Box Layout Model346 4. Nest another box inside the first. You can nest flexboxes inside each other. Simply apply the box display type to inner elements that will show the display. 5. Modify the order in which elements appear. Normally elements appear in the order in which they were pla...

  • Page 375

    Book III Chapter 4 Using Alternative PositioningFlexible Box Layout Model347The following style sheet is used to apply a flex grid style to this page: div { border: 1px solid black; } #a { width: 300px; height: 200px; display: box; box-orient: horizontal; ...

  • Page 376

    Flexible Box Layout Model348 4. Elements e and f should each take half of d. Use the box-flex attribute to give these elements equal weight. 5. Change the ordinal group of e so it appears after f. The box-ordinal-group attribute indicates the order in which an element will be displayed inside i...

  • Page 377

    Book III Chapter 4 Using Alternative PositioningFlexible Box Layout Model349 Figure 4-11: This standard layout uses flexbox. Though you can’t tell from the screen shot, this page uses HTML5 through-out, including the new semantic tags (See the sidebar for a discussion of semantic tags) and a f...

  • Page 378

    Flexible Box Layout Model350 box-orient: horizontal; -moz-box-orient: horizontal; -webkit-box-orient: horizontal; -ms-box-orient: horizontal; } #nav { box-flex: 1; -moz-box-flex: 1; -webkit-box-flex: 1; ...

  • Page 379

    Book III Chapter 4 Using Alternative Positioning351Determining Your Layout SchemeThe flexbox approach is really promising. When you get used to it, flexbox is less mysterious than the float approach, and far more flexible than abso-lute positioning. Essentially, my page uses a fixed width div and...

  • Page 380

    352 Determining Your Layout Schemequite as flexible as the floating layout techniques, and it’s hard to make it work right in older browsers.Sometimes, fixed and relative positioning schemes are handy, as in the exam-ple introduced in the fixed menu example described in this chapter.The flexbox...

  • Page 381

    actionURI(http://www.dummies.com/extras/html5css3aio):Visit actionURI(http://www.dummies.com/extras/html5css3aio):www.dummies.com/extras/html5css3aioactionURI(http://www.dummies.com/extras/html5css3aio): for more on JavaScript Libraries.Part IVClient-Side Programming with JavaScriptwww.freepdf-b...

  • Page 382

    Contents at a Glance Contents at a GlanceChapter 1: Getting Started with JavaScript . . . . . . . . . . . . . . . . . . . . . .355Working in JavaScript......................................................................................................355Writing Your First JavaScript Program ......

  • Page 383

    Chapter 1: Getting Started with JavaScriptIn This Chapter✓ Adding JavaScript code to your pages✓ Setting up your environment for JavaScript✓ Creating variables✓ Inputting and outputting with modal dialogs✓ Using concatenation to build text data✓ Understanding data types✓ Using strin...

  • Page 384

    Working in JavaScript356 ✦ It’s a real programming language. Don’t let anybody tell you otherwise. Sure, JavaScript doesn’t have all the same features as a monster, such as C++ or VB.NET, but it still has all the hallmarks of a complete program-ming language. ✦ It’s not Java. Sun Micr...

  • Page 385

    Writing Your First JavaScript Program357Book IV Chapter 1Getting Started with JavaScriptThings will go wrong when you write JavaScript code, and the browser is responsible for telling you what went wrong. Chrome is by far the favorite browser for JavaScript programmers today because it has extre...

  • Page 386

    Writing Your First JavaScript Program358Here’s an overview of the code:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>HelloWorld.html</title> <script type = "text/javascript"> ...

  • Page 387

    Introducing Variables359Book IV Chapter 1Getting Started with JavaScriptbecause it’s easy to understand and use. Also, note that the dialog will be slightly different from browser to browser and between operating systems. There isn’t really a way to control more precisely how dialogs work, b...

  • Page 388

    Introducing Variables360The rest of the greeting happens in a second dialog box, shown in Figure 1-4. It incorporates the username supplied in the first dialog box. Your browser might or might not have the ‘prevent this page from creating additional dialogs’ checkbox. This is actually a nic...

  • Page 389

    Introducing Variables361Book IV Chapter 1Getting Started with JavaScriptVariables are simply places in memory for holding data. Any time you want a computer program to “remember” something, you can create a variable and store your information in it.Variables typically have the following char...

  • Page 390

    Using Concatenation to Build Better Greetings362This alert() statement has a parameter with no quotes. Because the parameter has no quotes, JavaScript understands that you don’t really want to say the text person. Instead, it looks for a variable named person and returns the value of that varia...

  • Page 391

    Using Concatenation to Build Better Greetings363Book IV Chapter 1Getting Started with JavaScript var person = ""; person = prompt("What is your name?"); alert("Hi there, " + person + "!"); </script> For the sake of brevity, I includ...

  • Page 392

    Understanding the String Object364Including spaces in your concatenated phrasesYou may be curious about the extra space between the comma and the quote in the output line: alert("Hi there, " + person + "!");This extra space is important because you want the output to look...

  • Page 393

    Understanding the String Object365Book IV Chapter 1Getting Started with JavaScriptIf you have a variable of type cow, it describes a pretty complicated thing. This thing might have properties, methods, and events, all of which can be used together to build a good representation of a cow. (Believ...

  • Page 394

    Understanding the String Object366 <script type = "text/javascript"> //from nameLength.html var person = prompt("Please enter your name."); var length = person.length; alert("Hi, " + person + "!"); alert("The ...

  • Page 395

    Understanding the String Object367Book IV Chapter 1Getting Started with JavaScript <script type = "text/javascript"> //from stringMethods.html var text = new String; text = prompt("Please enter some text."); alert("I'll shout it out:&...

  • Page 396

    Understanding Variable Types368 Here’s another cool thing about Komodo Edit. When you type text, Komodo understands that you’re talking about a string variable and automatically pops up a list of all the possible properties and methods of the string object. I wish I had that when I started do...

  • Page 397

    Understanding Variable Types369Book IV Chapter 1Getting Started with JavaScriptAdding numbersFirst, take a look at the following program: <script type = "text/javascript"> //from addNumbers.html var x = 5; var y = 3; var sum = x + y; alert(x + " plus &q...

  • Page 398

    Understanding Variable Types370 ✦ Everything works as expected. The behavior of this program works as expected. That’s important because it’s not always true. (You can see an example of this behavior in the next section — I love writing code that blows up on purpose!)Adding the user’s n...

  • Page 399

    Understanding Variable Types371Book IV Chapter 1Getting Started with JavaScriptMany languages, such as C and Java, have all kinds of rules about defining data. If you create a variable in one of these languages, you have to define exactly what kind of data will go in the variable, and you can’...

  • Page 400

    Changing Variables to the Desired Type372Strangely, the behavior of the plus sign is different here, even though the statement result = x + y is identical in the two code snippets.In this second case, x and y are numbers. The plus operator has two entirely different jobs. If it’s surrounded by ...

  • Page 401

    Changing Variables to the Desired Type373Book IV Chapter 1Getting Started with JavaScriptUsing variable conversion toolsThe conversion functions are incredibly powerful, but you only need them if the automatic conversion causes you problems. Here’s how they work: ✦ parseInt() is used to con...

  • Page 402

    Changing Variables to the Desired Type374You can see the program works correctly in Figure 1-11. Figure 1-11: Now the program asks for input and correctly returns the sum. Conversion methods allow you to ensure that the data is in exactly the format you want.www.freepdf-books.com

  • Page 403

    Chapter 2: Talking to the PageIn This Chapter✓ Introducing the Document Object Model✓ Responding to form events✓ Connecting a button to a function✓ Retrieving data from text fields✓ Changing text in text fields✓ Sending data to the page✓ Working with other text-related form elements...

  • Page 404

    Understanding the Document Object Model376 3. Turn on the web developer toolbar. Use the F12 key, View ➪ Developer ➪ Developer Tools or Tools ➪ Developer Tools from the menu. (It may vary based on your version of Chrome or your operating system.) 4. Go to the Console tab. The Developer To...

  • Page 405

    Book IV Chapter 2Talking to the PageUnderstanding the Document Object Model377 The Console tab is far more involved and powerful than I’m letting on here. Chapter 3 of this mini-book goes into all kinds of details about how to use this powerful tool to figure out what’s going on in your page...

  • Page 406

    Understanding the Document Object Model378The page has white text on a blue background, but there’s no CSS! Instead, it has a small script that changes the DOM directly, controlling the page colors through code.<!DOCTYPE html><html lang = "en-US"> <head> <met...

  • Page 407

    Book IV Chapter 2Talking to the PageManaging Button Events379don’t get this discussion. This example is probably the only time you’ll see this trick because I show a better way in the next example.) ✦ Use a DOM reference to change the style colors. That long “trail of breadcrumbs” synt...

  • Page 408

    Managing Button Events380 ✦ Each button has a special attribute called onclick: The onclick attribute is an event handler. This is special because it allows you to apply some sort of action to the button press. The action (a single line of JavaScript code) assigned to onclick will happen each t...

  • Page 409

    Book IV Chapter 2Talking to the PageManaging Button Events381 </fieldset> </form> </body></html>Adding a function for more … functionalityThe buttons work, but the program seems quite inefficient. First, buttons can only have one line of code attached to the on...

  • Page 410

    Managing Button Events382 1. There’s a function called makeBlue()in the script area. The function keyword allows you to collect one or more commands and give them a name. In this case, I’m giving that nasty document.body.style nonsense a much more sensible name — makeBlue(). 2. The parenth...

  • Page 411

    Book IV Chapter 2Talking to the PageManaging Button Events383 document.body.style.backgroundColor = color; } // end changeColor </script> </head> <body> <h1>Click a button to change the color</h1> <form action = ""> <fi...

  • Page 412

    Managing Text Input and Output384Embedding quotes within quotesTake a careful look at the onclick lines in the code in the preceding sec-tion. You may not have noticed one important issue:onclick is an HTML parameter, and its value must be encased in quotes. The parameter happens to be a function...

  • Page 413

    Book IV Chapter 2Talking to the PageManaging Text Input and Output385 Figure 2-5: I’ve typed a name into the top textbox. When you click the button, something exciting happens, demonstrated by Figure 2-6. Figure 2-6: I got a greeting! With no alert box! Clearly, form-based input and output ...

  • Page 414

    Managing Text Input and Output386 1. Create a user interface. In web pages, the user interface is usually built of HTML and CSS. 2. Identify events the program should respond to. If you have a button, users will click it. (If you want to guarantee they click it, put the text “Launch the Missi...

  • Page 415

    Book IV Chapter 2Talking to the PageManaging Text Input and Output387 onclick = "sayHi()"/> <input type = "text" id = "txtOutput" /> </fieldset> </form> </body></html>As you look over the c...

  • Page 416

    Writing to the Document388the object it represents. If you want, you can think of it as making the textbox into a variable.Note that I call the variable txtName, just like the original textbox. This variable refers to the text field from the form, not the value of that text field. After I have a ...

  • Page 417

    Book IV Chapter 2Talking to the PageWriting to the Document389 So what are the exceptions? Single-element tags (like <img> and <input>) don’t contain any HTML, so obviously reading or changing their inner HTML doesn’t make sense. Table elements can often be read from but not chan...

  • Page 418

    Writing to the Document390Amazingly enough, this page can make changes to itself dynamically. It isn’t simply changing the values of form fields, but changing the HTML.Preparing the HTML frameworkTo see how the page changes itself dynamically, begin by looking at the HTML body for innerHTML.htm...

  • Page 419

    Book IV Chapter 2Talking to the PageWorking with Other Text Elements391The first step (as usual with web forms) is to extract data from the input ele-ments. Note that I can create a variable representation of any DOM element, not just form elements. The divOutput variable is a JavaScript represe...

  • Page 420

    Working with Other Text Elements392When the user clicks the button, the contents of all the fields (even the password and hidden fields) appear on the bottom of the page, as shown in Figure 2-10. Figure 2-10: Now you can see what was in everything. Building the formHere’s the HTML (otherText....

  • Page 421

    Book IV Chapter 2Talking to the PageWorking with Other Text Elements393 <div id = "output"> </div> </body>The code may be familiar to you if you read about form elements in Book I, Chapter 7. A few things are worth noting for this example: ✦ An ordinary text ...

  • Page 422

    Working with Other Text Elements394 // from otherText.html function processForm(){ //grab input from form var txtNormal = document.getElementById("txtNormal"); var pwd = document.getElementById("pwd"); var hidden = document.getElementById(...

  • Page 423

    Book IV Chapter 2Talking to the PageWorking with Other Text Elements395my programs write code just like I do, so I add newline characters every-where I’d add a carriage return if I were writing the HTML by hand.Understanding generated sourceWhen you run the program in the preceding section, yo...

  • Page 424

    Working with Other Text Elements396Here’s what’s going on: The view source command (on most browsers) doesn’t actually view the source of the page as it currently stands. It goes back to the server and retrieves the page, but displays it as source rather than rendered output. As a result, t...

  • Page 425

    Book IV Chapter 2Talking to the PageWorking with Other Text Elements397 7. The “trail of breadcrumbs” shows where you are. You can see exactly what tags are active by looking at the bottom of the developer screen. 8. You can also see which CSS files are currently active. As described in Bo...

  • Page 426

    Working with Other Text Elements398This very sneaky trick uses JavaScript to generate the source code of the page as it currently stands: 1. Begin with the javascript: identifier. When you begin an address with javascript, the browser immediately renders the rest of the address as a JavaScript i...

  • Page 427

    Chapter 3: Decisions and DebuggingIn This Chapter✓ Making decisions with conditions✓ Working with nested if statements and switch✓ Repeating with for loops✓ Repeating with while loops✓ Understanding the difference between bugs and crashes✓ Using the debugger console✓ Debugging your ...

  • Page 428

    Making Choices with if400 Figure 3-1: Tim Berners-Lee gets a special greeting. Figure 3-2: Apparently, this guy isn’t famous enough. This program (and the next few) uses a basic HTML set up to take informa-tion from a text field, respond to a button click, and print output in a desig-nated a...

  • Page 429

    Book IV Chapter 3Decisions and DebuggingMaking Choices with if401 id = "txtInput" value = "Tim Berners-Lee" /> <button type = "button" onclick = "checkName()"> click me </button> </...

  • Page 430

    Making Choices with if402parentheses). If the condition is true, all of the code in the following set of braces is executed. 6. Write code to execute if the condition is true. Create a set of squiggly braces after the condition. Any code inside these braces will execute if the condition is true....

  • Page 431

    Book IV Chapter 3Decisions and DebuggingMaking Choices with if403} else { lblOutput.innerHTML = "Do I know you?";} // end if I don’t repeat all the HTML code for these examples to save space. Please look on the book’s website to see the appropriate HTML code that uses these example...

  • Page 432

    Making Choices with if404 //less than 32 alert("It's freezing!"); } else { //between 32 and 60 alert("It's cold."); } // end 'freezing if' } else { //We're over 60 if (temp < 75){ //between 60 and...

  • Page 433

    Book IV Chapter 3Decisions and DebuggingMaking Choices with if405 6. Indentation and comments are not optional. As the code becomes more complex, indentation and comment characters become more critical. Make sure your indentation accurately reflects the beginning and end of each if statement, a...

  • Page 434

    Managing Repetition with for Loops406 3. End each case with the break statement. End each case with the break statement. This indicates that you’re done thinking about cases, and it’s time to pop out of this data structure. If you don’t explicitly include the break statement, you’ll get ...

  • Page 435

    Book IV Chapter 3Decisions and DebuggingManaging Repetition with for Loops407 Figure 3-3: This program counts from one to ten. Setting up the web pageThe same web page is used to demonstrate three different kinds of for loops. As usual, the HTML code sets everything up. Here’s the HTML code th...

  • Page 436

    Managing Repetition with for Loops408 1. The body calls an initialization function. Often you’ll want some code to happen when the page first loads. One common way to do this is to attach a function call to the onload attribute of the body element. In this example, I call the init() function...

  • Page 437

    Book IV Chapter 3Decisions and DebuggingManaging Repetition with for Loops409 finished forming. The init() function is called when the body loads. Inside that function, I assign a value to the global output variable. Here’s how the main JavaScript and the init() method code looks: var outpu...

  • Page 438

    Managing Repetition with for Loops410 6. Change the variable. The third part of a for statement somehow changes the counting variable. The most common way to change the variable is to add one to it. The i++ syntax is a shortcut for “add one to i.” 7. Build a code block for repeated code. U...

  • Page 439

    Book IV Chapter 3Decisions and DebuggingManaging Repetition with for Loops411This statement also means, “Add one to i.” In the standard for loop, I use that variation because it’s very easy. When programmers decided to make a new variation of C, they called the new language C++. Get it? It...

  • Page 440

    Managing Repetition with for Loops412 3. Subtract 1 from i on each pass. The -- operator works much like ++, but it subtracts 1 from the variable.Counting by fivesCounting by fives (or any other value) is pretty trivial after you know how for loops work. Here’s the byFive() code called by the...

  • Page 441

    Book IV Chapter 3Decisions and Debugging413Building while LoopsUnderstanding the Zen of for loopsFor loops might seem complex, but they really aren’t. The key to making a good for loop is understanding that the for statement has three parts. All three parts of the statement refer to the same va...

  • Page 442

    Building while Loops414Here’s the HTML code used for two different while examples:<body> <h1>While Loop Demo</h1> <p>The password is 'HTML5'</p> <form action = ""> <fieldset> <button type = "button" onclick...

  • Page 443

    Book IV Chapter 3Decisions and DebuggingBuilding while Loops415 4. Build the condition. The condition is the heart of a while loop. The condition must be con-structed so the loop happens at least once (ensure this by comparing the condition to the variable initialization). When the condition is ...

  • Page 444

    Building while Loops416 ✦ Change the condition inside the loop: Somewhere inside the loop code, you need to have statements that will eventually make the condition false. If you forget this part, your loop will never end. (How does the variable change?) This example is a good example of a while...

  • Page 445

    Book IV Chapter 3Decisions and DebuggingBuilding while Loops417 3. Build a Boolean sentry variable. The keepGoing variable is special. Its entire job is to indicate whether the loop should continue or not. It is a Boolean variable, meaning it will only contain the values true or false. 4. Use ke...

  • Page 446

    Managing Errors with a Debugger418Managing Errors with a DebuggerBy the time you’re writing loops and conditions, things can go pretty badly in your code. Sometimes it’s very hard to tell what exactly is going on. Fortunately, modern browsers have some nice tools that help you look at your co...

  • Page 447

    Book IV Chapter 3Decisions and DebuggingManaging Errors with a Debugger419 6. Refresh the page. In the main browser, use the refresh button or F5 key to refresh the page. The page may initially be blank. That’s fine — it means the program has paused when it encountered the function. 7. Your ...

  • Page 448

    Managing Errors with a Debugger420 Figure 3-7: The Chrome debugger makes it easy to figure out what’s happening. I personally think the debugger built into Chrome is one of the best out there, but it’s not the only choice. If you’re using Firefox, the excellent Firebug extension adds the...

  • Page 449

    Book IV Chapter 3Decisions and DebuggingManaging Errors with a Debugger421 4. Switch to the console tab. The Console tab switches to console mode. This is particularly interest-ing when the program is paused, as you can investigate and change the nature of the page in real time. 5. Change a styl...

  • Page 450

    Managing Errors with a Debugger422the code print a value to the console. Normally you’ll do this only when your code is not functioning properly to see what’s going on. You might use something like this: console.log(“current value of i” + i). The user typically doesn’t know there is a c...

  • Page 451

    Book IV Chapter 3Decisions and DebuggingManaging Errors with a Debugger423 Figure 3-8: The debugging console has useful information here! It would be great if the debugger told you exactly what is wrong, but nor-mally there’s a bit of detective work involved in deciphering error messages. It a...

  • Page 452

    Managing Errors with a Debugger424 something else. That’s somewhat helpful, but the real strategy is to know that something is probably wrong with this line, and you need to look it over carefully. At some point, you’ll probably realize that line 10 should have a single equals sign. Rather th...

  • Page 453

    Book IV Chapter 3Decisions and Debugging425Managing Errors with a Debuggergood to write down what you expect so you’ll know if you got there. (Professional programmers are usually required to list expectations before they write a single line of code.) For this example, when the user clicks the ...

  • Page 454

    426 Managing Errors with a Debugger 7. Step to your suspicious code. If you’re worried about a condition (which is very common), use the debugger tools to step to that condition, but don’t run it yet. (In most debuggers, a highlighted line is about to be run.) 8. Look at the relevant variabl...

  • Page 455

    Book IV Chapter 3Decisions and DebuggingManaging Errors with a Debugger427If a debugger can find syntax errors, wouldn’t it be awesome if debuggers could find logic errors too? This issue turns out to be one of the big unsolved problems of computer science. Researchers are still trying to disco...

  • Page 456

    428 Book IV: Client-Side Programming with JavaScriptwww.freepdf-books.com

  • Page 457

    Chapter 4: Functions, Arrays, and ObjectsIn This Chapter✓ Passing parameters into functions✓ Returning values from functions✓ Functions and variable scope✓ Producing basic arrays✓ Retrieving data from arrays✓ Building a multidimensional array✓ Creating objects✓ Building object co...

  • Page 458

    Breaking Code into Functions430you can do with a program. A program using functions is basically a program full of subprograms. After you define your functions, they’re just like new JavaScript commands. In a sense, when you add functions, you’re adding to JavaScript.To explain functions bett...

  • Page 459

    Book IV Chapter 4Functions, Arrays, and ObjectsBreaking Code into Functions431Musicians call this a road map, and that’s a great name for it. A road map is a high-level view of how you progress through the song. In the road map, you don’t worry about the details of the particular verse or cho...

  • Page 460

    Passing Data to and from Functions432 <body> <h1>Using Basic Functions</h1> <form action = ""> <fieldset> <button type = "button" onclick = "makeSong()"> make song </button> ...

  • Page 461

    Book IV Chapter 4Functions, Arrays, and ObjectsPassing Data to and from Functions433 <!DOCTYPE HTML> <html lang = "en"> <head> <title>param.html</title> <meta charset = "UTF-8" /> <style type = "text/css&...

  • Page 462

    Passing Data to and from Functions434This code incorporates a couple of important new ideas. (The following list is just the overview; the specifics are coming in the following sections.) ✦ These functions return a value. The functions no longer do their own alerts. Instead, they create a value...

  • Page 463

    Book IV Chapter 4Functions, Arrays, and ObjectsPassing Data to and from Functions435Here’s what changed: ✦ The purpose of the function has changed. The function is no longer designed to output some value to the screen. Instead, it now provides text to the main program, which can do whatever i...

  • Page 464

    Passing Data to and from Functions436the verse() function from the main program will become the value of the variable verseNumber inside the function.You can define a function with as many parameters as you want. Each parameter gives you the opportunity to send a piece of information to the funct...

  • Page 465

    Book IV Chapter 4Functions, Arrays, and ObjectsManaging Scope437A whole lotta concatenating is going on, but it’s essentially the same code as the original verse() function. This one’s just a lot more flexible because it can handle any verse. (Well, if the function has been preloaded to under...

  • Page 466

    Managing Scope438This program defines two variables. In the main code, globalVar is defined, and localVar is defined inside a function. If you run the program in debug mode while watching the variables, you can see how they behave. Figure 4-2 shows what the program looks like early in the run. F...

  • Page 467

    Book IV Chapter 4Functions, Arrays, and ObjectsBuilding a Basic Array439 Be sure to use Step Into (down arrow) rather than Step Over (up arrow) on the “remote control” toolbar for this example. When Step Over encounters a function, it runs the entire function as one line rather than looking a...

  • Page 468

    Building a Basic Array440The following code shows a basic demonstration of arrays: <script type = "text/javascript"> //from genres.html //creating an empty array var genre = new Array(5); //storing data in the array genre[0] = "flight simulation...

  • Page 469

    Book IV Chapter 4Functions, Arrays, and ObjectsBuilding a Basic Array441 Figure 4-5: This data came from an array. Using arrays with for loopsThe main reason to use arrays is convenience. When you have a lot of information in an array, you can write code to work with the data quickly. Whenever y...

  • Page 470

    Building a Basic Array442 ✦ Do something with each element. Because i goes from 0 to 9 (the array indices), I can easily print each value of the array. In this example, I simply add to an output string. ✦ Note the newline characters. The \n combination is a special character that tells JavaSc...

  • Page 471

    Book IV Chapter 4Functions, Arrays, and ObjectsBuilding a Basic Array443 output.innerHTML = ""; for (verseNumber = 1; verseNumber < distractionList.length; verseNumber++){ output.innerHTML += verse(verseNumber); output.innerHTML += chorus(); ...

  • Page 472

    Working with Two-Dimension Arrays444Working with Two-Dimension ArraysArrays are useful when working with lists of data. Sometimes, you encounter data that’s best imagined in a table. For example, what if you want to build a distance calculator that determines the distance between two cities? Th...

  • Page 473

    Book IV Chapter 4Functions, Arrays, and ObjectsWorking with Two-Dimension Arrays445Figure 4-7: It’s a Tale of Two Cities. You even get the distance between them!www.freepdf-books.com

  • Page 474

    Working with Two-Dimension Arrays446 Yep, you can have three, four, or more dimension arrays in programming, but don’t worry about that yet. (It may make your head explode.) Most of the time, one or two dimensions are all you need.This program is a touch longer than some of the others, so I bre...

  • Page 475

    Book IV Chapter 4Functions, Arrays, and ObjectsWorking with Two-Dimension Arrays447because the row is an array, you need the column number within that array. So, distance[1][3] means go to row 1 (“New York”) of distance. Within that row go to element 3 (“London”) and return the resulting ...

  • Page 476

    Working with Two-Dimension Arrays448Creating a main() functionThe main() function handles most of the code for the program. function main(){ var output = ""; var from = getCity(); var to = getCity(); var result = distance[from][to]; output = "...

  • Page 477

    Book IV Chapter 4Functions, Arrays, and ObjectsCreating Your Own Objects449 I didn’t actually write the program in the order I showed it to you in the pre-ceding steps. Sometimes it makes more sense to go “inside out.” I actually created the data structure first (as an ordinary table on pap...

  • Page 478

    Creating Your Own Objects450 //view property values alert("the critter's name is " + critter.name);The way it works is not difficult to follow: 1. Create a new Object. JavaScript has a built-in object called Object. Make a variable with the new Object() syntax, and you’ll build yo...

  • Page 479

    Book IV Chapter 4Functions, Arrays, and ObjectsCreating Your Own Objects451 //create a method critter.talk = function(){ msg = "Hi! My name is " + this.name; msg += " and I'm " + this.age; alert(msg); } // end method // call the talk method critter.talk();This ...

  • Page 480

    Creating Your Own Objects452 6. You can then refer to the method directly. After you define an object with a method, you can invoke it. For exam-ple, if the critter object has a talk method, use critter.talk() to invoke this method.Building a reusable objectThese objects are nice, but what if yo...

  • Page 481

    Book IV Chapter 4Functions, Arrays, and ObjectsCreating Your Own Objects453later if you wish. Each property should begin with this and a period. If you want your object to have a color property, you’d say something like this.color = “blue”. My example uses the local parameters to define the...

  • Page 482

    Introducing JSON454 ✦ Modify the class properties as you wish: You can change the values of any of the class properties. In my example, I change the name and age of the second critter just to show how it’s done. ✦ Call class methods: Because the critter class has a talk() method, you can us...

  • Page 483

    Book IV Chapter 4Functions, Arrays, and ObjectsIntroducing JSON455 The reason JavaScript arrays are so useful is that they are in fact objects. When you create an array in JavaScript, you are building an object with numeric property names. This is why you can use either array or object syntax for...

  • Page 484

    Introducing JSON456 "New York" : { "Indianapolis": 648, "New York": 0, "Tokyo": 6760, "London": 3470 }, "Tokyo" : { "Indianapolis": 6476, "New York": 6760, ...

  • Page 485

    Book IV Chapter 4Functions, Arrays, and ObjectsIntroducing JSON457You can even go with some kind of hybrid: alert(distance["London"].Tokyo); JSON has a number of important advantages as a data format: ✦ Self-documenting: Even if you see the data structure on its own without any ...

  • Page 486

    458 Book IV: Client-Side Programming with JavaScriptwww.freepdf-books.com

  • Page 487

    Chapter 5: Getting Valid InputIn This Chapter✓ Extracting data from drop-down lists✓ Working with multiple-selection lists✓ Getting data from check boxes and radio groups✓ Validating input with regular expressions✓ Using character, boundary, and repetition operators✓ Using pattern mem...

  • Page 488

    Getting Input from a Drop-Down List460 Figure 5-1: The user selects from a predefined list of valid choices. Building the formWhen you’re creating a predefined list of choices, create the HTML form first because it defines all the elements you’ll need for the function. The code is a standard...

  • Page 489

    Book IV Chapter 5Getting Valid InputGetting Input from a Drop-Down List461 In this and most examples in this chapter, I add CSS styling to clean up each form. Be sure to look over the styles if you want to see how I did it. Note also that I’m only showing the HTML right now. The entire code lis...

  • Page 490

    Managing Multiple Selections462Managing Multiple SelectionsYou can use the select object in a more powerful way than the method I describe in the preceding section. Figure 5-2 shows a page with a multiple-selection list box. Figure 5-2: You can pick multiple choices from this list. To make mult...

  • Page 491

    Book IV Chapter 5Getting Valid InputManaging Multiple Selections463 <label> Select the language(s) you know. (ctrl-click to select multiple lines) </label> <select id = "selLanguage" multiple = "multiple" ...

  • Page 492

    Managing Multiple Selections464The key is to recognize that a list of option objects inside a select object is really a kind of array, not just one value. You can look more closely at the list of objects to see which ones are selected, which is essentially what the showChoices() function does: ...

  • Page 493

    Book IV Chapter 5Getting Valid InputCheck, Please: Reading Check Boxes465 5. Assign the current element to a temporary variable. The currentOption variable holds a reference to each option element in the original select object as the loop progresses. currentOption = selLanguage[i]; 6. ...

  • Page 494

    Check, Please: Reading Check Boxes466 Figure 5-3: You can pick your toppings here. Choose as many as you like. Building the check box pageTo build the check box page shown in Figure 5-3, start by looking at the HTML: <body> <h1>What do you want on your pizza?</h1> <f...

  • Page 495

    Book IV Chapter 5Getting Valid InputCheck, Please: Reading Check Boxes467 Note the labels have a for attribute which connects each label to the corresponding check box. When you connect a label to a check box in this way, the user can activate the check box by clicking on the box or the label. Th...

  • Page 496

    Working with Radio Buttons468Working with Radio ButtonsRadio button groups appear pretty simple, but they’re more complex than they seem. Figure 5-4 shows a page using radio button selection. Figure 5-4: One and only one member of a radio group can be selected at one time. The most important ...

  • Page 497

    Book IV Chapter 5Getting Valid InputInterpreting Radio Buttons469 name = "weapon" id = "radNoodle" value = "wet noodle" /> <label for = "radNoodle">Wet Noodle</label> <button type = &...

  • Page 498

    Working with Regular Expressions470 if (currentWeapon.checked){ var selectedWeapon = currentWeapon.value; } // end if } // end for var output = document.getElementById("output"); var response = "<h2>You defeated the dragon w...

  • Page 499

    Book IV Chapter 5Getting Valid InputWorking with Regular Expressions471 Figure 5-5: This page is a mess. No username, plus an invalid e-mail and phone number. ✦ An entry must appear in each field. This one is reasonably easy — just check for non-null values. ✦ The e-mail must be in a vali...

  • Page 500

    Working with Regular Expressions472 //create an empty error message errors = ""; //check name - It simply needs to exist if (name == ""){ errors += "please supply a name \n"; } // end if //check email...

  • Page 501

    Book IV Chapter 5Getting Valid InputWorking with Regular Expressions473 ✦ Match the regular expression against the e-mail address. The next line checks to see whether the e-mail address is a match to the regu-lar expression. The result is true if the expression matches an e-mail address or null...

  • Page 502

    Working with Regular Expressions474OperatorDescriptionSample PatternMatchesDoesn’t Match $End of string a$Bananaapple[characters]Any of a list of characters in braces [abcABC]AD[char range]Any character in the range [a-zA-Z]F9 \dAny single numerical digit \d\d\d-\d\d\d\d123-4567The-thing \bA wo...

  • Page 503

    Book IV Chapter 5Getting Valid InputWorking with Regular Expressions475 Figure 5-6: This tool allows you to test regular expressions. The top textbox accepts a regular expression, and the second text field con-tains text to examine. You can practice the examples in the following sections to see ...

  • Page 504

    Working with Regular Expressions476This match is the simplest type. I’m simply looking for the existence of the needle (bigCorp) in a haystack (the e-mail address stored in email). If big-Corp is found anywhere in the text, the match is true, and I can do what I want (usually process the form o...

  • Page 505

    Book IV Chapter 5Getting Valid InputWorking with Regular Expressions477This list of characters is sometimes called a character class. For example, /b[aeiou]g/ matches on bag, beg, big, bog, or bug. This method is a really quick way to check a lot of potential matches. You can also specify a char...

  • Page 506

    Working with Regular Expressions478 The .* combination is especially useful, because you can use it to improve matches like e-mail addresses: /^.*@bigCorp\.com$/ does a pretty good job of matching e-mail addresses in a fictional company. ✦ Specifying the number of matches: You can use braces (...

  • Page 507

    Book IV Chapter 5Getting Valid InputNew HTML5/CSS3 Tricks for Validation479New HTML5/CSS3 Tricks for ValidationHTML5 and CSS3 add a few more tricks to simplify validation, and they are absolutely wonderful.While you can always use JavaScript and regular expressions to validate your pages (as desc...

  • Page 508

    New HTML5/CSS3 Tricks for Validation480 Figure 5-7: The new HTML5 form elements have automatic validation. Please look over the code for html5validation.html on the website — the code hasn’t changed substantially from Book I, Chapter 7. The CSS code is new, so I reproduce that here: &...

  • Page 509

    Book IV Chapter 5Getting Valid InputNew HTML5/CSS3 Tricks for Validation481Adding a patternThe pattern attribute allows you to specify a regular expression used to validate the form. If the content matches the regular expression, the field will be considered valid. (See the “Working with Regula...

  • Page 510

    New HTML5/CSS3 Tricks for Validation482Not all browsers support placeholder text. Other browsers will simply ignore the placeholder attribute. Likewise, if the field is already filled in, the placeholder will not be visible. For these reasons, it is still preferred to add a label so users know wh...

  • Page 511

    Chapter 6: Drawing on the CanvasIn This Chapter✓ Adding a canvas to your HTML page✓ Using colors, patterns, and gradients✓ Drawing paths and geometric shapes✓ Working with images✓ Pixel manipulationT he canvas element is one of the most interesting new developments in HTML5. Although t...

  • Page 512

    Canvas Basics484Setting up the canvasTo use the <canvas> tag, build a web page with a <canvas> element in it. Typically you’ll provide width, height, and id parameters: <canvas id = "drawing" width = "200" height = "200"> <...

  • Page 513

    Book IV Chapter 6Drawing on the CanvasCanvas Basics485The draw() function illustrates all of the main ideas of working with the canvas tag. Here’s how you build a basic drawing: ✦ Create a variable reference to the canvas: Use the standard getEle-mentById() mechanism to create a variable refe...

  • Page 514

    Fill and Stroke Styles486You can also draw text directly onto the canvas in various fonts and colors. You can add shadow effects to your text elements, or even images.The canvas object gives you access to the underlying data of an image. This allows you to perform any kind of transformation you w...

  • Page 515

    Book IV Chapter 6Drawing on the CanvasFill and Stroke Styles487that the rgb function must go in quotes like any other color value. If you want to include alpha, add a fourth parameter that is a 0–1 value. Transparent red would be rgba(255, 0, 0, 0.5). ✦ hsl and hsla: The new hsl and hsla colo...

  • Page 516

    Fill and Stroke Styles488The output of this code is shown in Figure 6-2. Figure 6-2: These gradient patterns were created by code. A linear gradient is a pattern of colors that blend into each other along a straight-line path. To define a linear gradient: ✦ Create a variable to hold the grad...

  • Page 517

    Book IV Chapter 6Drawing on the CanvasFill and Stroke Styles489text value that can be evaluated as a CSS color. You can use any of the mechanisms described in the color section of this part. At a minimum, you should define two color stops, one for the beginning, and one for the end. ✦ Apply the...

  • Page 518

    Fill and Stroke Styles490that is designed to be tiled. (See Book VIII, Chapter 4 for complete informa-tion on how to build tiled patterns using free software.) Many sources of tiled patterns exist on the web as well. After you’ve got an image you want to use as a fill pattern, here’s how to i...

  • Page 519

    Book IV Chapter 6Drawing on the CanvasDrawing Essential Shapes491A pattern is simply an image. Building a pattern is relatively straightforward: 1. Get access to an image. You’ll need a JavaScript image object to serve as the basis of your pat-tern. There’s a number of ways to do this, but ...

  • Page 520

    Drawing Essential Shapes492 ✦ strokeRect(x, y, w, h): Draws a box with upper-left corner (x,y) and size (w,h). The box is not filled in, but the outline is drawn in the currently-defined strokeStyle and using the current lineWidth. Figure 6-4 illustrates a couple of rectangles. Figure 6-4: Yo...

  • Page 521

    Book IV Chapter 6Drawing on the CanvasDrawing Essential Shapes493Figure 6-5 shows a canvas with embedded text. Figure 6-5: Text is embedded into the canvas. Text is drawn onto canvas much like a rectangle. The first step is to pick the desired font. Canvas fonts are created by assigning a font ...

  • Page 522

    Drawing Essential Shapes494Adding shadowsYou can add shadows to anything you draw on the canvas. Shadows are quite easy to build. They require a number of methods of the context object: ✦ shadowOffsetX: Determines how much the shadow will be moved along the X axis. Normally this will be a valu...

  • Page 523

    Book IV Chapter 6Drawing on the CanvasDrawing Essential Shapes495 //clear background con.fillStyle = "white"; con.fillRect(0,0, 200, 200); // draw font in red con.fillStyle = "red"; con.font = "18pt sans-serif&q...

  • Page 524

    Working with Paths496Working with PathsMore complex shapes are created using the path mechanism. A path is simply a series of commands “played back” by the graphics context. You can think of it as a recording of pen motions. Here’s an example that draws a blue triangle with a red border: f...

  • Page 525

    Book IV Chapter 6Drawing on the CanvasWorking with Paths497The technique for drawing a path is not terribly complicated, but it does involve new steps: 1. Generate the graphics context. All <canvas> programs begin by creating a variable for the canvas and another variable for the graphics...

  • Page 526

    Working with Paths498 Remember, the lineTo() method doesn’t actually draw a line! It simply indicates your path. The path is not visible until you execute a stroke(), closePath(), or fill() command.Line-drawing optionsWhenever you are using stroke commands, you can modify the line width and sty...

  • Page 527

    Book IV Chapter 6Drawing on the CanvasWorking with Paths499 con.lineTo(50, 10); con.lineTo(60, 40); con.stroke(); con.closePath(); con.lineJoin = "miter"; con.strokeStyle = "green" con.beginPath(); con.moveTo(70, 40); con.lineTo(80, 10); con.line...

  • Page 528

    Working with Paths500Drawing arcs and circlesArcs and circles are part of the path mechanism. They are created much like lines, as they are executed as part of a path. After the path is complete, use the stroke() or fill() command to actually draw the arc or circle.Arcs and circles are both creat...

  • Page 529

    Book IV Chapter 6Drawing on the CanvasWorking with Paths501 con.closePath(); con.stroke(); //full circle filled con.beginPath(); con.arc(220, 220, 50, 0, Math.PI*2, true); con.closePath(); con.fill(); }This code generates the image shown in Figure 6-9. Figure 6-9: Draw ci...

  • Page 530

    Working with Paths502 If you’re familiar with radian measurement, you might think the angles are upside down (typically, π /2 is north and 3* π /2 is south). The angles are reversed because Y increases downwards in computer systems.Drawing quadratic curvesThe canvas element also supports two ...

  • Page 531

    Book IV Chapter 6Drawing on the CanvasWorking with Paths503 drawDot(190, 190, "blue"); //mark control points with red drawDot(100, 10, "red"); } // end draw function drawDot(x, y, color){ con.fillStyle = color; con.beginPath(); con.arc(...

  • Page 532

    Working with Paths504 Figure 6-11: The Bézier curve uses two control points. function draw(){ //from bezier.html drawing = document.getElementById("drawing"); con = drawing.getContext("2d"); con.strokeStyle = "black"; ...

  • Page 533

    Book IV Chapter 6Drawing on the CanvasImages505ImagesAlthough HTML has long had support for images, the canvas interface adds new life to web images. Images can be displayed inside a canvas, where they can be integrated with the vector-drawing techniques of the canvas API. You can also select a p...

  • Page 534

    Images506The following JavaScript code displays the image in the canvas: function draw(){ //from image.html var drawing = document.getElementById("drawing"); var con = drawing.getContext("2d"); var goofyPic = document.getElementById("goofyPic"); con.d...

  • Page 535

    Book IV Chapter 6Drawing on the CanvasImages507image.onload = finishDrawing;function finishDrawing(){ //rest of drawing code goes here}Drawing part of an imageSometimes you’ll want to draw a small part of the original image. Figure 6-13 illustrates a program focusing in on the center of the g...

  • Page 536

    Manipulating Pixels508 ✦ Size of destination: The last two parameters describe the size of the destination image on the canvas.The “draw only part of an image” technique described here is quite useful because it allows you to combine several images into a single image (some-times called a ...

  • Page 537

    Book IV Chapter 6Drawing on the CanvasManipulating Pixels509 r = imgData.data[index]; g = imgData.data[index + 1]; b = imgData.data[index + 2]; a = imgData.data[index + 3]; //manipulate color values r -= 20; g += 50; b -= 30; a = a; ...

  • Page 538

    Manipulating Pixels510 3. Make a loop to handle the rows. Image data is broken into rows and columns. Each row goes from 0 to the height of the canvas, so make a for loop to iterate through the rows. 4. Make another loop to handle the columns. Inside each row is data from 0 to the width of the ...

  • Page 539

    Chapter 7: Animation with the CanvasIn This Chapter✓ Working with images✓ Managing transformations✓ Handling keyboard input✓ Building basic animationsT he <canvas> tag (introduced in Chapter 6 of this minibook) adds some long-needed graphical support to HTML. In this chapter, you s...

  • Page 540

    Transformations512 2. Move the center with translate(). The origin (0, 0) starts in the upper-left corner of the canvas by default. Normally you’ll build your transformed objects on the (new) origin and move the origin to place the object. If you translate (50, 50) and then draw an image at (0...

  • Page 541

    Book IV Chapter 7Animation with the CanvasTransformations513This program creates a new coordinate system containing a translation, rotation, and scale. It draws an image in the new coordinate system. It then reverts to the standard coordinate system and draws a rectangular frame.This program will...

  • Page 542

    Transformations514If you’re more comfortable with degrees, you can use this formula to convert: radians = degrees * (Math.PI / 180). 5. Scale the coordinate system by X and Y. You can change the apparent width and height of your new coordinate system by indicating new scale values. Scaling is...

  • Page 543

    Book IV Chapter 7Animation with the CanvasAnimation515point. This time, turn left 90 degrees and then go forward five steps. Are you in the same place? You might need to experiment a bit to get things working the way you expect. ✦ Transform the system then draw on the origin: Most of the draw-i...

  • Page 544

    Animation516 3. Evaluating the current state. Each sprite is really a data element. During every frame, determine if anything important has happened: Did the user press a key? Is an ele-ment supposed to move? Did a sprite leave the screen? Did two sprites conk into each other? 4. Modifying sprit...

  • Page 545

    Book IV Chapter 7Animation with the CanvasAnimation517Initializing the animationAs usual, the body onload mechanism will be used to start up some code as soon as the page has finished loading. However, the page now has two functions. The init() function handles initialization, and the draw() func...

  • Page 546

    Animation518 //draw the image con.drawImage(goofyPic, SPR_WIDTH/-2, SPR_HEIGHT/-2, SPR_WIDTH, SPR_HEIGHT); con.restore(); } // end draw Although the code may seem a little involved, it doesn’t do really do any-thing new. Here’s what it does, step by step: 1. Clears...

  • Page 547

    Book IV Chapter 7Animation with the CanvasAnimation519draw the image so its center is at the origin. Set X to zero minus half the image’s width, and Y to zero minus half the image’s height. 6. Closes the transformation. Use the restore() method to finish defining the temporary coordinate sys...

  • Page 548

    Animation520 if (x < 0){ x = CANV_WIDTH; } if (y > CANV_HEIGHT){ y = 0; } // end if if (y < 0){ y = CANV_HEIGHT; } } // end wrapThe wrap code is very similar to the rotation program. It has a few different features. Here’s what it does: 1. Keep...

  • Page 549

    Book IV Chapter 7Animation with the CanvasReading the Keyboard521 if (y < 0){ dy *= -1; } } // end bounceReading the KeyboardThe keyboard is a primary input technology, especially for desktop machines. The standard way to read the keyboard is to set up special func-tions called e...

  • Page 550

    Reading the Keyboard522 Figure 7-2: This page reports which key you pressed. Managing basic keyboard inputThis particular example demonstrates basic keyboard-checking as well as the more sophisticated technique used in simpleGame. Here’s how the basic version works: 1. Assigns a function to on...

  • Page 551

    Book IV Chapter 7Animation with the CanvasReading the Keyboard523Moving an image with the keyboardYou can achieve a form of interactivity by having an image move in response to keyboard motion. Figure 7-3 illustrates this technique, but it really isn’t sat-isfying to see in a book. As usual, y...

  • Page 552

    Reading the Keyboard524 function init(){ drawing = document.getElementById("drawing"); con = drawing.getContext("2d"); goofyPic = document.getElementById("goofyPic"); document.onkeydown = updateKeys; setInterval(draw, 100); } function upd...

  • Page 553

    Book IV Chapter 7Animation with the CanvasReading the Keyboard525 } if (y > CANV_HEIGHT){ y = 0; } // end if if (y < 0){ y = CANV_HEIGHT; } } // end wrap //keyboard constants K_LEFT = 37; K_RIGHT = 39; K_UP = 38;K_DOWN = 40; K_SPACE = 32; <...

  • Page 554

    Reading the Keyboard526 This is a very simple keyboard input mechanism. It’s fine for basic user input, but in gaming we use much more sophisticated input techniques including a mechanism called polling, which allows multiple keys at a time. In addition, the modern web includes mobile devices, ...

  • Page 555

    actionURI(http://www.dummies.com/extras/html5css3aio):Visit actionURI(http://www.dummies.com/extras/html5css3aio):www.dummies.com/extras/html5css3aioactionURI(http://www.dummies.com/extras/html5css3aio): for more on using templates with PHP.Part VServer-Side Programming with PHPwww.freepdf-books...

  • Page 556

    Contents at a Glance Contents at a GlanceChapter 1: Getting Started on the Server . . . . . . . . . . . . . . . . . . . . . . . .529Introducing Server-Side Programming .........................................................................529Installing Your Web Server .............................

  • Page 557

    Chapter 1: Getting Started on the ServerIn This Chapter✓ Introducing server-side programming✓ Testing your installation✓ Inspecting phpinfo( )✓ Writing HTML with embedded PHP✓ Understanding various types of quotation✓ Managing concatenation and interpolation✓ Using heredocs to simp...

  • Page 558

    Introducing Server-Side Programming530The client has a big problem, though. Programs written on the client usually have a form of forced amnesia (no long-term memory). For security reasons, client-side applications can’t store information in files and can’t interact with other programs on the...

  • Page 559

    Book V Chapter 1Getting Started on the ServerIntroducing Server-Side Programming531server available and place the file in a specific place on your computer for the server to serve it. You can’t run a PHP file directly from your desktop. It must be placed in a special place — often, the htdoc...

  • Page 560

    Installing Your Web Server532PythonThe Python language is used in a number of contexts, including server-side programming. Although Python has become much more popular as of late, it still isn’t used as frequently as PHP for this purpose.PHPPHP was born from a collection of modifications for Pe...

  • Page 561

    Book V Chapter 1Getting Started on the ServerInspecting phpinfo()533 ✦ A database backend: Modern websites rely heavily on data, so a pro-gram that can manage your data needs is very important. I use MySQL (a free and powerful tool) for this. Book VI is entirely dedicated to creating data with...

  • Page 562

    Inspecting phpinfo()534To test everything, make the PHP version of the famous “Hello World!” program. Follow these steps to make your first PHP program: 1. Open a text editor to create a new file. PHP files are essentially plain text files, just like HTML and JavaScript. You can use the same...

  • Page 563

    Book V Chapter 1Getting Started on the ServerInspecting phpinfo()535 If you see the actual PHP code rather than the results shown in Figure 1-1, you probably didn’t refer to the page correctly. Please check the following: ✦ Is the file in the right place? Your file must be in htdocs or on a...

  • Page 564

    Building HTML with PHP536configured on your server, which may not mean much now. If you have trouble with PHP and ask me for help, however, it’s the first thing I’ll ask you for. An experienced developer can do a lot of troubleshooting by looking over a phpinfo so it’s a handy skill to kno...

  • Page 565

    Book V Chapter 1Getting Started on the ServerBuilding HTML with PHP537interpret the HTML and then print that (the HTML) to the user. Therefore, all your code gets interpreted twice: first on the server to generate the HTML and then on the user’s machine to generate the output display.If you’...

  • Page 566

    Building HTML with PHP538 5. View the file in a web browser, as shown in Figure 1-2. The address of a web page begins with the http:// protocol and then the server name. If the page is on the local machine, the server name is localhost, which corresponds directly to your htdocs directory. If yo...

  • Page 567

    Book V Chapter 1Getting Started on the ServerCoding with Quotation Marks539Coding with Quotation MarksThere are many different ways to use print. The following are all legal ways to print text, but they have subtle differences: print ("<p>Hello World!</p>"); print (&...

  • Page 568

    Working with Variables PHP-Style540Working with Variables PHP-StyleVariables are extremely important in any programming language and no less so in PHP. A variable in PHP always begins with a $.A PHP variable can be named almost anything. There are some reserved words that you can’t name a varia...

  • Page 569

    Book V Chapter 1Getting Started on the ServerWorking with Variables PHP-Style541ConcatenationConcatenation is the process of joining smaller strings to form a larger string. (See Book IV, Chapter 1 for a description of concatenation as it’s applied in JavaScript.) PHP uses the period (·) symb...

  • Page 570

    Working with Variables PHP-Style542The previous code takes the variable output with the value World and concatenates it to Hello when printed. Next, it adds the variable output to the number 5. When PHP sees the plus sign, it interprets the values on either side of it as numbers. Because output h...

  • Page 571

    Book V Chapter 1Getting Started on the ServerBuilding HTML Output543This process is called interpolation. Because all PHP variables begin with dollar signs, you can freely put variables right inside your string values, and when PHP sees a variable, it will automatically replace that variable wit...

  • Page 572

    Building HTML Output544$output .= " </tr> \n";$output .= "</table> \n"; print $outputHowever, using quotes to generate HTML output is inconvenient for the fol-lowing reasons: ✦ The $output variable must be initialized. Before adding anything to the $output varia...

  • Page 573

    Book V Chapter 1Getting Started on the ServerBuilding HTML Output545 Figure 1-5: This page was created with the heredoc mechanism. Heredocs have some great advantages: ✦ All carriage returns are preserved. There’s no need to put in any newline characters. Whatever carriage returns are in ...

  • Page 574

    Building HTML Output546 ✦ A heredoc must be closed with the same word it was opened with. ✦ The closing word for the heredoc must be on its own line with no other symbols or spaces, just the word followed by a semicolon. ✦ You can’t indent the closing word for the heredoc; there can’t b...

  • Page 575

    Book V Chapter 1Getting Started on the ServerBuilding HTML Output547This option (switching back and forth) is generally used when you have a lot of HTML code with only a few simple PHP variables. I prefer the heredoc approach, but feel free to experiment and find out what system works for you.Wh...

  • Page 576

    548 Book V: Server-Side Programming with PHPwww.freepdf-books.com

  • Page 577

    Chapter 2: PHP and HTML FormsIn This Chapter✓ Understanding the relationship between HTML and PHP✓ Using the date( ) function✓ Formatting date and time information✓ Creating HTML forms designed to work with PHP✓ Choosing between get and post data transmission✓ Retrieving data from you...

  • Page 578

    Exploring the Relationship between PHP and HTML550Embedding PHP inside HTMLThe PHP code has some interesting characteristics: ✦ It’s structured mainly as an HTML document. The doctype definition, document heading, and initial H1 heading are all ordinary HTML. Begin your page as you do any HTM...

  • Page 579

    Book V Chapter 2PHP and HTML FormsExploring the Relationship between PHP and HTML551Viewing the resultsIf you view showDate.php in your browser, you won’t see the PHP code. Instead, you’ll see an HTML page. It’s even more interesting when you use your browser to view the page source. Here...

  • Page 580

    Sending Data to a PHP Program552Sending Data to a PHP ProgramYou can send data to a PHP program from an HTML form. For an example of this technique, see askName.html in Figure 2-2. Figure 2-2: This HTML page has a simple form. HTML forms (described fully in Book I, Chapter 7) allow the user to ...

  • Page 581

    Book V Chapter 2PHP and HTML FormsSending Data to a PHP Program553 <body> <form action = "greetUser.php" method = "get"> <fieldset> <label>Please enter your name</label> <input type = "text" ...

  • Page 582

    Sending Data to a PHP Program554by the form. I want this data to be processed by a program called greetUser.php, so I set greetUser.php as the action: <form action = "greetUser.php" method = "get"> 3. Set the form’s method attribute to get. The method attr...

  • Page 583

    Book V Chapter 2PHP and HTML FormsSending Data to a PHP Program555<input type = "submit" value = "click me"/> or<button type = "submit">click me</button> Specify submit as the button’s type attribute to ensure the button sends the data to the se...

  • Page 584

    Choosing the Method of Your Madness556HTML tags you want. (I’m keeping this example as simple as possible, although I’d normally add some CSS styles to make the output less boring.) 3. Add a PHP segment. Somewhere in the page, you’ll need to switch to PHP syntax so that you can extract the...

  • Page 585

    Book V Chapter 2PHP and HTML FormsChoosing the Method of Your Madness557 ✦ POST: The post method passes the data to the server through a mechanism called environment variables. This mechanism makes the form elements slightly more secure because they aren’t displayed in public as they are with...

  • Page 586

    Choosing the Method of Your Madness558 ✦ Each field/value pair is listed. The question mark is followed by each field name and its associated value in the following format:URL?field1=value1&field2=value2 ✦ An equal sign (=) follows each field name. Each field name is separated by the valu...

  • Page 587

    Book V Chapter 2PHP and HTML FormsChoosing the Method of Your Madness559You might wonder how I knew what fields the Google engine expects. If the program uses get, just use the intended form to make a search and look at the resulting URL. Some testing and experience told me that only the q field ...

  • Page 588

    Choosing the Method of Your Madness560 ✦ Data is gathered and encoded, just like it is in the get method. When the user clicks the submit button, the data is encoded in a format similar to the get request, but it’s not attached to the URL. ✦ The form data is sent directly to the server. The...

  • Page 589

    Book V Chapter 2PHP and HTML FormsChoosing the Method of Your Madness561 Sanitizing filters all begin with the phrase FILTER_SANITIZE, and they are designed to strip off various types of characters. FILTER_SANITIZE_STRING removes or converts any special characters, and FILTER_SANITIZE_EMAIL remo...

  • Page 590

    Choosing the Method of Your Madness562There are few more filters, and some have optional parameters, so you may need to look at the online documentation to get all the details. Ninety percent of the time, you’ll just stick with the default FILTER_SANITIZE_STRING filter.The filter_input techniqu...

  • Page 591

    Book V Chapter 2PHP and HTML FormsRetrieving Data from Other Form Elements563Retrieving Data from Other Form ElementsIt’s just as easy to get data from drop-down lists and radio buttons as it is to get data from text fields. In PHP (unlike JavaScript), you use exactly the same technique to extr...

  • Page 592

    Retrieving Data from Other Form Elements564 <p> <label>What is your name?</label> <select name = "name"> <option value = "Roger"> Roger the Shrubber </option> <option ...

  • Page 593

    Book V Chapter 2PHP and HTML FormsRetrieving Data from Other Form Elements565There’s nothing too crazy about this code. Please note the following features: ✦ The action attribute is set to monty.php. This page (monty.html) will send data to monty.php, which should be in the same directory on ...

  • Page 594

    Retrieving Data from Other Form Elements566 It’s no coincidence that monty.html uses monty.css and calls monty.php. I deliberately gave these files similar names so it will be easy to see how they fit together.This program works like most PHP programs: It loads data from the form into variables...

  • Page 595

    Book V Chapter 2PHP and HTML FormsRetrieving Data from Other Form Elements567 2. Embed your PHP inside an HTML framework. Use your standard HTML framework as the starting point for your PHP documents, too. The results of your PHP code should still be standards-compliant HTML. Use the <?php an...

  • Page 596

    Retrieving Data from Other Form Elements568 b. Check each check box variable. If it exists, the corresponding check box was checked, so she must be a witch (and she must weigh the same as a duck — you’ve really got to watch this movie). After testing for the existence of all the check boxes,...

  • Page 597

    Chapter 3: Using Control StructuresIn This Chapter✓ Getting used to conditions✓ Using if, else if, and else✓ Using switch structures✓ Working with while and for loops✓ Using comparison operatorsC omputer programs are most interesting when they appear to make decisions. PHP has many of t...

  • Page 598

    Building the Classic if Statement570Building the Classic if StatementThe if statement is the powerhouse of computer programming. Take a look at Figure 3-1 to see it in action. This program might be familiar if you read Book IV already. It rolls a standard six-sided die, and then displays that di...

  • Page 599

    Book V Chapter 3Using Control StructuresBuilding the Classic if Statement571This program is much like the if.html program in Book IV, Chapter 3. I do all the same things here as in that program. However, PHP and JavaScript are a little different, and that’s part of the game of programming. Appr...

  • Page 600

    Building the Classic if Statement572The process is eerily familiar: 1. Begin with a standard HTML template. As always, PHP is encased in HTML. There’s no need to switch to PHP until you get to the part that HTML can’t do: that is, rolling dice and responding to the roll. 2. Add a link to let...

  • Page 601

    Book V Chapter 3Using Control StructuresBuilding the Classic if Statement573 <p> <a href = "highLow.php">roll again</a> </p> <?php $roll = rand(1,6); print <<<HERE <p> <img src = "images/dado_$roll.png" ...

  • Page 602

    Building the Classic if Statement574Table 3-1 Comparison OperatorsComparisonDiscussionA == BTrue if A is equal to BA != BTrue if A is not equal to BA < BTrue if A is less than B (if they are numeric) or earlier in the alphabet (for strings)A > BTrue if A is larger than B (numeric) or later...

  • Page 603

    Book V Chapter 3Using Control StructuresBuilding the Classic if Statement575 Figure 3-4: Now there are three possible comments, thanks to the else if structure. If the roll is 1 or 2, the program reports Low. If the roll is 3 or 4, it says Middle; and if it’s 5 or 6, the result is High. This i...

  • Page 604

    Building the Classic if Statement576The if statement is the only part of this program that’s new. It’s not terribly shocking. 1. Begin with a standard condition. Check whether the roll is greater than 4. If so, say High. If the first con-dition is true, the computer evaluates the code in the...

  • Page 605

    Book V Chapter 3Using Control StructuresBuilding the Classic if Statement577The interesting thing happens when the user submits the form. The program calls itself! This time, though, ownForm recognizes that the user has sent some data and processes that information, giving the result shown in Fi...

  • Page 606

    Making a switch578 </fieldset> </form>HERE;} // end if?></body></html>Making a program “do its own stunts” like this is pretty easy. The key is using an if statement. However, begin by thinking about the behavior. In this example, the program revolves around the...

  • Page 607

    Book V Chapter 3Using Control StructuresMaking a switch579 Figure 3-7: The Magic 8 Ball uses a switch. The code for this program uses the switch structure. Take a look at how it’s done:<!doctype html><html lang="en"><head> <meta charset="UTF-8"> &l...

  • Page 608

    Making a switch580 case 7: print "<p><img src=\"images/8ball7.png\" alt = \"Ask your mother\" /></p>"; break; case 8: print "<p><img src=\"images/8ball8.png\" alt = \"The answer is in the question\" />...

  • Page 609

    Book V Chapter 3Using Control StructuresLooping with for581 7. Use the default clause to handle any unexpected behavior. The default section of the switch structure is used to handle any situ-ation that wasn’t covered by one of the previously defined cases. It’s a good idea to always include...

  • Page 610

    Looping with for582As you can see, Figure 3-8 prints a lot of dice. In fact, it prints 100 dice. This would be tedious to do by hand, but that’s exactly the kind of stuff comput-ers are so good at.The following code explains all:<!doctype html><html lang="en"><head>...

  • Page 611

    Book V Chapter 3Using Control StructuresLooping with for583 2. Add an initializer. for loops usually center around a specific integer variable, sometimes called the sentry variable. The first part of the for loop sets up the ini-tial value of that variable. Often, the variable is initialized to ...

  • Page 612

    Looping with while584 ✦ Check whether you rolled a 6. For some strange reason, my obsession with sixes continues. If the roll is a 6, add 1 to the $sixCount variable. By the end of the loop, this will contain the total number of sixes rolled.if($userNumber == 6){ $sixCount++;} // end if ✦ ...

  • Page 613

    Book V Chapter 3Using Control StructuresLooping with while585 ✦ A modifier: You must somehow modify the value of the sentry variable. It’s important that the modification statement happen somewhere inside the loop. In a for loop, you almost always add or subtract to modify a variable. In a wh...

  • Page 614

    Looping with while586 1. Initialize $userNumber. For this loop, $userNumber is the sentry variable. The initialization needs to guarantee that the loop runs exactly once. Because the condition will be ($userNumber != 6), I need to give $userNumber a value that clearly isn’t 6. 999 will do the ...

  • Page 615

    Chapter 4: Working with ArraysIn This Chapter✓ Creating one-dimensional arrays✓ Making the most of multidimensional arrays✓ Using foreach loops to simplify array management✓ Breaking a string into an arrayI n time, arrays will become one of the most important tools in your tool-box. They ...

  • Page 616

    Using One-Dimensional Arrays588Filling an arrayAn array is a container, so it’s a lot more fun if you put something in it. You can refer to an array element by adding an index (an integer) representing which element of the array you’re talking about.Say I have the following array:$spanish = a...

  • Page 617

    Book V Chapter 4Working with ArraysUsing One-Dimensional Arrays589print "<pre> \n";print_r($spanish);print "</pre> \n";The print_r() function is a special debugging function. It allows you to pass an entire array, and it prints out the array in an easy-to-read form...

  • Page 618

    Using Loops with Arrays590I use the print_r() function to quickly see the contents of the array. The preloaded array is shown in Figure 4-2. Figure 4-2: This array was preloaded, but the user can’t tell the difference. Using Loops with ArraysArrays and loops are like peanut butter and jelly; ...

  • Page 619

    Book V Chapter 4Working with ArraysUsing Loops with Arrays591 //just print them out with a loop print "<p> \n"; for ($i = 0; $i < sizeof($books);$i++){ print $books[$i] . "<br />\n"; } // end for print "</p> \n"; //use the...

  • Page 620

    Using Loops with Arrays592foreach ($books as $book){ print $book . " <br />\n";} // end foreachprint "</p> \n";The foreach loop is a special version of the for loop that simplifies working with arrays. Here’s how it works: 1. Use the foreach keyword to begin th...

  • Page 621

    Book V Chapter 4Working with ArraysUsing Loops with Arrays593 Many languages have variations of the foreach loop, but they differ greatly in the details. In PHP, the array comes first, then the scalar (non-array) variable. In Python, the order is inverted. In most languages (like PHP), the scalar...

  • Page 622

    Introducing Associative Arrays594 $books = array("Creating the XHTML Foundation", "Styling with CSS", "Using Positional CSS for Layout", "Client-Side Programming with JavaScript", ...

  • Page 623

    Book V Chapter 4Working with ArraysIntroducing Associative Arrays595$myStuff["email"] = "andy@aharrisbooks.net"; print $myStuff["name"];Associative arrays are different than normal (numeric-indexed) arrays in some subtle but important ways: ✦ The order is undefine...

  • Page 624

    Introducing Associative Arrays596 Figure 4-5: This variable stores data in an associative array. Here’s how it works: 1. Begin the foreach loop as normal. The associative form of the foreach loop begins just like the regular one: foreach ($_SERVER as $key => $value){ 2. Identify the ...

  • Page 625

    Book V Chapter 4Working with ArraysIntroducing Multidimensional Arrays597however you wish. I used a definition list because it’s a natural way to display key/value pairs. A list of definitions is keys and values.print <<<HERE <dt>$key</dt> <dd>$value</dd> HER...

  • Page 626

    Introducing Multidimensional Arrays598The following code shows the basic HTML form:<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Distance.html</title> <style type="text/css"> form { width: 600px; ...

  • Page 627

    Book V Chapter 4Working with ArraysIntroducing Multidimensional Arrays599 2. Create a select object to determine where the user is leaving. This form element will be called from because it represents the city the user is coming from. Note that the value is an integer that will relate to the vari...

  • Page 628

    Breaking a String into an Array600</head><body> <?php //get variables from form $cityName = array("Indianapolis", "New York", "Tokyo", "London"); $from = filter_input(INPUT_POST, "from"); $to = filter_input(INPUT_POST, ...

  • Page 629

    Book V Chapter 4Working with ArraysBreaking a String into an Array601 ✦ explode: explode takes one parameter as a delimiter and splits the string into an array based upon that one parameter. ✦ preg_ split: If you require regular expressions, using preg_split is the way to go. split allows you...

  • Page 630

    Breaking a String into an Array602 Figure 4-8: A string exploded into an array. Creating arrays with preg_splitpreg_split is a bit more complicated. preg_split uses regular expres-sions to split a string into an array, which can make it a bit slower than explode.preg_split looks exactly like exp...

  • Page 631

    Book V Chapter 4Working with ArraysBreaking a String into an Array603 print "<pre>\n"; print_r($theArray); print "</pre>\n"; ?> </body></html> Figure 4-9: The e-mail address split into an array. Recall that regular expressions are encased...

  • Page 632

    604 Book V: Server-Side Programming with PHPwww.freepdf-books.com

  • Page 633

    Chapter 5: Using Functions and Session VariablesIn This Chapter✓ Creating functions to manage your code’s complexity✓ Enhancing your code by using functions✓ Working with variable scope✓ Getting familiar with session variables✓ Incorporating session variables into your codeP HP progr...

  • Page 634

    Creating Your Own Functions606Rolling dice the old-fashioned wayBefore I show you how to improve your code with functions, look at a pro-gram that doesn’t use functions so you have something to compare with.The following rollDice.php program creates five random numbers and dis-plays a graphic f...

  • Page 635

    Book V Chapter 5Using Functions and Session VariablesCreating Your Own Functions607 width = "100px" height = "100px" />HERE; ?> </div> </body></html>Here are some interesting features of this code: ✦ The built-in rand()function...

  • Page 636

    Creating Your Own Functions608 </head> <body> <h1>RollDice 2</h1> <h2>Uses Functions</h2> <?php function rollDie(){ $roll = rand(1,6); $image = "dado_$roll.png"; print <<< HERE <img src = &q...

  • Page 637

    Book V Chapter 5Using Functions and Session VariablesCreating Your Own Functions609 5. Indent the code that makes up your function. Use indentation to indicate which code is part of your function. In this case, the function generates the random number and prints an image tag based on that random...

  • Page 638

    Creating Your Own Functions610Managing variable scopeTwo kinds of scope are in PHP: global and local.If you define a variable outside a function, it has the potential to be used inside any function. If you define a variable inside a function, you can access it only from inside the function in whi...

  • Page 639

    Book V Chapter 5Using Functions and Session VariablesManaging Persistence with Session Variables611 <meta charset="UTF-8"> <title>helloFunction</title></head><body> <?php function getName(){ return "World"; } print "<...

  • Page 640

    Managing Persistence with Session Variables612 Figure 5-3: This page displays a roll, the number of rolls, and the total rolls so far. The interesting feature of rollDice3.php happens when you reload the page. Take a look at Figure 5-4. This is still rollDice3.php, after I refreshed the browser...

  • Page 641

    Book V Chapter 5Using Functions and Session VariablesManaging Persistence with Session Variables613Understanding session variablesThe rollDice3.php program acts differently. It has a mechanism for keeping track of the total rolls and number of visits to the page.When a visitor accesses your websi...

  • Page 642

    Managing Persistence with Session Variables614{ $count++;{ $_SESSION["count"] = $count;{ } else {{ //if count doesn't exist, this is our first pass,{ //so initialize both session variables{ $_SESSION["count"] = 1;{ $_SESSION["total"] = 0;{ $coun...

  • Page 643

    Book V Chapter 5Using Functions and Session VariablesManaging Persistence with Session Variables615 2. Check for the existence of the session variables. Like form variables, session variables may or may not exist when the program is executed. If this is the first pass through the program, the se...

  • Page 644

    Managing Persistence with Session Variables616 //if count doesn't exist, this is our first pass, //so initialize both session variables $_SESSION["count"] = 1; $_SESSION["total"] = 0; $count = 1; If you want to reset your sessions for testing purposes, you c...

  • Page 645

    Chapter 6: Working with Files and DirectoriesIn This Chapter✓ Saving to text files✓ Reading from text files✓ Reading a file as an array✓ Parsing delimited text data✓ Working with file and directory functionsA n important part of any programming language is file manipulations. Whether y...

  • Page 646

    Text File Manipulation618Writing text to filesThis section details the functions needed to access and write to a file, such as how to request access to a file from PHP with the fopen() function, write to the file using the fwrite() function, and let PHP know you are done with the file with the fc...

  • Page 647

    Book V Chapter 6Working with Files and DirectoriesText File Manipulation619 Be careful, though, because if you specify this mode (w) for the fopen() function and use the fwrite() function, you will completely overwrite any-thing that may have been in the file. Don’t use w if there’s anything ...

  • Page 648

    Text File Manipulation620more information), you can use the file in your PHP code. You can either read from the file, or you can write to the file with the fwrite() function.Depending on what mode you specify when you opened the file with the fopen() function, the fwrite() function either overwr...

  • Page 649

    Book V Chapter 6Working with Files and DirectoriesText File Manipulation621 Figure 6-1: Here’s a standard form that asks for some contact information. I didn’t reproduce the code for this form here because it’s basic HTML. Of course, it’s available on the book’s companion website, and ...

  • Page 650

    Text File Manipulation622 Figure 6-2: This program has responded to the file input. The more interesting behavior of the program is not visible to the user. The program opens a file for output and prints the contents of the form to the end of that file. Here are the contents of the data file aft...

  • Page 651

    Book V Chapter 6Working with Files and DirectoriesText File Manipulation623 <meta charset=”UTF-8”> <title>addContact.html</title> <link rel = “stylesheet” type = “text/css” href = “contact.css” /></head><body> <?php //read data from form $lNa...

  • Page 652

    Text File Manipulation624 4. Open the file in append mode. You might have hundreds of entries. Using append mode ensures that each entry goes at the end of the file, rather than overwriting the previ-ous contents. 5. Write the data to the file. Using the fwrite() or fputs() function writes the ...

  • Page 653

    Book V Chapter 6Working with Files and DirectoriesText File Manipulation625Reading from the fileIf you can write data to a file, it would make sense that you could read from that file as well. The readContact.php program displayed in Figure 6-3 pulls the data saved in the previous program and di...

  • Page 654

    Using Delimited Data626The procedure is similar to writing the file, but it uses a while loop. 1. Open the file in read mode. Open the file just as you do when you write to it, but use the r designa-tor to open the file for read mode. Now you can use the fgets() func-tion on the file. 2. Create ...

  • Page 655

    Book V Chapter 6Working with Files and DirectoriesUsing Delimited Data627you’ll need a more organized way to store the data. You can see how to use relational databases for this type of task in Book VI, but for now, another compromise is fine for simpler data tasks. You can store data in a very...

  • Page 656

    Using Delimited Data628 5. Write the data to the file. The fwrite() function does this job with ease. 6. Close the file. This part (like most of the program) is identical to the earlier version of the code.Here’s the code for addContactCSV.php in its entirety:<!DOCTYPE html><html lan...

  • Page 657

    Book V Chapter 6Working with Files and DirectoriesUsing Delimited Data629Viewing CSV data directlyIf you look at the resulting file in a plain text editor, it looks like Figure 6-4. Figure 6-4: The data is separated by tab characters and each entry is on its own line. Of course, CSV data isn’...

  • Page 658

    Using Delimited Data630This is an easy way to store large amounts of data because you can use the spreadsheet to manipulate the data. Of course, relational databases (described in Book VI) are even better, but this is a very easy approach for relatively simple data sets. I’ve built many data en...

  • Page 659

    Book V Chapter 6Working with Files and DirectoriesUsing Delimited Data631 Figure 6-6: This program creates an HTML table from the data in the file. In this program, I read the contents of a CSV file and display it in an HTML table. It’s not terribly different than reading any other text file, ...

  • Page 660

    Using Delimited Data632 4. Explode each line into its own array. You have got to love a function with a violent name, especially when it’s really useful. Use the explode command to separate the line into its component parts. For this example, I break on the tab (\t) character because that’...

  • Page 661

    Book V Chapter 6Working with Files and DirectoriesWorking with File and Directory Functions633 The file() function is appealing, but it isn’t perfect for every situation. It’s great as long as the file size is relatively small, but if you try to load in a very large file, you will run into me...

  • Page 662

    Working with File and Directory Functions634Here is an example of the opendir() function (see the “Generating the list of file links” section to see the opendir() function in action). This function stores a directory handle to the C:\xampp\htdocs\XFD\xfd5.7 directory in the $directoryHandle v...

  • Page 663

    Book V Chapter 6Working with Files and DirectoriesWorking with File and Directory Functions635Here is an example of the chdir(). This function changes to the C:\xampp\htdocs\XFD\xfd5.6 directory:chdir("C:\xampp\htdocs\XFD\xfd5.6");When you change to a directory, you’re then free to wr...

  • Page 664

    Working with File and Directory Functions636 3. Read the next file from the directory pointer. The readDir() function reads the next file in and stores it to a variable ($currentFile). $currentFile = readDir($dp); 4. Append the current file to an array. If you simply assign a file to an array w...

  • Page 665

    Book V Chapter 6Working with Files and DirectoriesWorking with File and Directory Functions637If you want just one particular file type, you can use regular expressions to filter the files. If I had wanted only the .txt and .dat files from the direc-tory, I could have run the file’s array throu...

  • Page 666

    638 Book V: Server-Side Programming with PHPwww.freepdf-books.com

  • Page 667

    Chapter 7: Exceptions and ObjectsIn This Chapter✓ Introducing PHP objects✓ Creating a constructor✓ Adding properties and methods to objects✓ Using access modifiers to protect data✓ Building sub-classes with inheritance✓ Trapping for errors with exception handlingP HP has become a crit...

  • Page 668

    Object-Oriented Programming in PHP640described in Book IV, Chapter 4 as a feature of JavaScript. PHP also supports object-oriented programming, but does it in a slightly different way. JavaScript and PHP both support object-oriented programming, but the details are very different. If you’re com...

  • Page 669

    Object-Oriented Programming in PHP641Book V Chapter 7Exceptions and Objects 3. Define a property. If you define a variable inside a class, it becomes a property. Properties are much like variables, but they live inside a class. The keyword public indicates that the variable will be available to ...

  • Page 670

    Object-Oriented Programming in PHP642Using your brand-new classWhat you did in simpleCritter.php was create the definition of a class. It’s like writing a recipe. This file contains the instructions for building a class, but you’ll generally use a class in a different project (or many — if ...

  • Page 671

    Object-Oriented Programming in PHP643If simpleCritter.php was about defining the class (writing a recipe), useCritter.php is about creating an instance (making cookies from the recipe). Here’s how it works: 1. Store useCritter.php and simpleCritter.php in the same directory. You can use comp...

  • Page 672

    Object-Oriented Programming in PHP644 5. Call a method just like a function call. Methods are very much like functions, except they are attached to a class instance. Call a method just like you would a function, but use the full name ($a->sayHi()). print $a->sayHi();The object in this s...

  • Page 673

    Object-Oriented Programming in PHP645 1. Defines properties as protected. There are three access modifiers you can use in PHP, which define the accessibility of a property or method. In the SimpleCritter class, you used public access throughout. The other modifiers you can use are private (which...

  • Page 674

    Object-Oriented Programming in PHP646 print "Hi, " . $a->getName() . "! <br />"; ?> </body></html>Figure 7-2 shows the (underwhelming) output of accessMod.php. A lot of times in programming the most important changes are not obvious to the user. F...

  • Page 675

    You’ve Got Your Momma’s Eyes: Inheritance647I hear you. The first object example (with public properties) was easy to understand and seems to work just fine. Then I suggest making it a little more complicated by protecting the properties, which makes you work a little harder by adding new met...

  • Page 676

    You’ve Got Your Momma’s Eyes: Inheritance648 Figure 7-3: This critter has an attitude. Building a critter based on another critterThere’s a new critter in town. This one has the same basic features, but a worse attitude. Take a look at the code to see what’s going on:<!doctype html>...

  • Page 677

    You’ve Got Your Momma’s Eyes: Inheritance649This example is an illustration of a very common programming situation, where I want a specialization of a previously defined class. I already have a Critter class, but I want a new kind of Critter. My new critter (the BitterCritter) begins with the...

  • Page 678

    Catching Exceptions650 This demonstration is just the barest glimpse into object-oriented program-ming. There is much more to this form of software development than I can describe in this introductory chapter, but the basics are all here. Though you might not immediately see the need to build you...

  • Page 679

    Catching Exceptions651you allow user input. This code listing explicitly traps for errors and reports them regardless of server settings:<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>try.php</title></head><bo...

  • Page 680

    Catching Exceptions652The most common line here is to call print($e->getMessage()). All exception objects have a getMessage() method, and this line reports the current error message.Knowing when to trap for exceptionsIf your server is set up for debugging (as XAMPP is by default), it won’t u...

  • Page 681

    actionURI(http://www.dummies.com/extras/html5css3aio):Visit actionURI(http://www.dummies.com/extras/html5css3aio):www.dummies.com/extras/html5css3aioactionURI(http://www.dummies.com/extras/html5css3aio): for more on SQLite and alternative data strategies.Part VIManaging Data with MySQLwww.freepd...

  • Page 682

    Contents at a Glance Contents at a GlanceChapter 1: Getting Started with Data . . . . . . . . . . . . . . . . . . . . . . . . . . .655Examining the Basic Structure of Data .........................................................................655Introducing MySQL ................................

  • Page 683

    Chapter 1: Getting Started with DataIn This Chapter✓ Understanding databases, tables, records, and fields✓ Introducing the relational data model✓ Introducing a three-tier model✓ Understanding MySQL data types✓ Getting started with MySQL and phpMyAdmin✓ Adding a password to your MySQL...

  • Page 684

    Examining the Basic Structure of Data656become the primary method for data management, and a standard language for this model, called SQL (Structured Query Language), has been developed.SQL has two major components: ✦ Data Definition Language (DDL) is a subset of SQL that helps you create and m...

  • Page 685

    Book VI Chapter 1Getting Started with DataExamining the Basic Structure of Data657Determining the fields in a recordIf you want to create a database, you need to think about what entity you’re describing and what fields that entity contains. In the table in the preceding section, I’m describ...

  • Page 686

    Examining the Basic Structure of Data658Data TypeDescriptionNotesDATEDate stored in YYYY-MM-DD formatCan be displayed in various formats.TIMETime stored in HH:MM:SS formatCan be displayed in various formats.CHAR(length)Fixed-length textAlways same length. Shorter text is padded with spaces. Longe...

  • Page 687

    Book VI Chapter 1Getting Started with DataExamining the Basic Structure of Data659exactly 100 bytes. You would then be able to figure out where each record is on the disk by multiplying the length of each record by the desired record’s index. (Record 0 would be at byte 0, record 1 is at 100, r...

  • Page 688

    Introducing MySQL660The definition for the e-mail contacts table may look like this:Field NameTypeLength (Bytes)ContactIDINTEGER11NameVARCHAR50CompanyVARCHAR30E-mailVARCHAR50Look over the table definition, and you’ll notice some important ideas: ✦ There’s now a contactID field. This field s...

  • Page 689

    Book VI Chapter 1Getting Started with DataIntroducing MySQL661 ✦ MS Access is the entry-level database system installed with most ver-sions of Microsoft Office. Although Access is a good tool for playing with data design, it has some well-documented problems handling the large number of reques...

  • Page 690

    Introducing MySQL662Understanding the three-tier architectureModern web programming often uses what’s called the three-tiered architec-ture, as shown in Table 1-2.Table 1-2 The Three-Tiered ArchitectureTierPlatform (software)ContentLanguageClientWeb browser (Chrome)Web pageHTML/CSS/JSServerWe...

  • Page 691

    Book VI Chapter 1Getting Started with DataSetting Up phpMyAdmin663without XAMPP, but you should really avoid the headaches of manual con-figuration, if you can. In this chapter, I do all MySQL through phpMyAdmin, but I show other alternatives in Chapters 2 and 5 of this minibook. ✦ Run MySQL f...

  • Page 692

    Setting Up phpMyAdmin664 Figure 1-2: I’ve turned on Apache and MySQL in the XAMPP control panel using the buttons. 2. Go to the XAMPP main directory in your browser. If you used the default installation, you can just point your browser to actionURI(http://localhost/xampp):http://localhost/xa...

  • Page 693

    Book VI Chapter 1Getting Started with DataSetting Up phpMyAdmin665 3. Find phpMyAdmin in the Tools section of the menu. The phpMyAdmin page looks like Figure 1-4. Figure 1-4: The phpMyAdmin main page. 4. Create a new database. Type the name for your database in the indicated text field. I ...

  • Page 694

    Setting Up phpMyAdmin666 1. Log into phpMyAdmin as normal. The main screen looks like Figure 1-5. Your copy might have a scary warning of gloom at the bottom. You’re about to fix that problem. Figure 1-5: Here’s the main phpMyAdmin screen. 2. Click the Privileges link to modify user priv...

  • Page 695

    Book VI Chapter 1Getting Started with DataSetting Up phpMyAdmin667 3. Edit the root user. Chances are good that you have only one user, called root (and maybe another called pma which is the phpMyAdmin user). The root account’s Password field says No. You’ll be adding a password to the root...

  • Page 696

    Setting Up phpMyAdmin668 Figure 1-9: That message can’t be good. Maybe I should have left it vulnerable. Don’t panic about the error in Figure 1-9. Believe it or not, this error is good. Up to now, phpMyAdmin was logging into your database as root without a password (just like the baddies w...

  • Page 697

    Book VI Chapter 1Getting Started with DataSetting Up phpMyAdmin669 1. Find the phpMyAdmin configuration file. You have to let phpMyAdmin know that you’ve changed the password. Look for a file in your phpMyAdmin directory called config.inc.php. (If you used the default XAMPP installation under...

  • Page 698

    Setting Up phpMyAdmin670Adding a userChanging the root password is the absolute minimum security measure, but it’s not the only one. You can add various virtual users to your system to protect it further.You’re able to log into your own copy of MySQL (and phpMyAdmin) as root because you’re ...

  • Page 699

    Book VI Chapter 1Getting Started with DataSetting Up phpMyAdmin671 Be sure to add a username and password. Typically, you use localhost as the host. 5. Create a database, if it doesn’t already exist. If you haven’t already made a database for this project, you can do so automatically with ...

  • Page 700

    Setting Up phpMyAdmin672 Your database users won’t usually be people. This idea is hard, particularly if you haven’t used PHP or another server-side language yet. The database users are usually programs you have written that access the database in your name.Using phpMyAdmin on a remote server...

  • Page 701

    Book VI Chapter 1Getting Started with DataSetting Up phpMyAdmin673 Don’t freak out if your screen looks a little different than Figure 1-15. Different hosting companies have slightly different rules and systems, so things won’t be just like this, but they’ll probably be similar. If you g...

  • Page 702

    Implementing a Database with phpMyAdmin674security system. On many hosting services, you must enter a password, and the system automatically creates a MySQL username with the same name as the database. Keep track of this information because you need it later when you write a program to work with ...

  • Page 703

    Book VI Chapter 1Getting Started with DataImplementing a Database with phpMyAdmin675 Figure 1-17: The main screen of the phpMy- Admin system. 2. Activate the database by clicking the database name in the left column. If the database is empty, an Add Table page, shown in Figure 1-18, appears...

  • Page 704

    Implementing a Database with phpMyAdmin676 Figure 1-19: Creating the contacts table. 4. Enter the field information. Type the field names into the grid to create the table. It should look like Figure 1-20. Figure 1-20: Enter field data on this form. In Figure 1-20, you can’t see it, but...

  • Page 705

    Book VI Chapter 1Getting Started with DataImplementing a Database with phpMyAdmin677 Figure 1-21: phpMy- Admin created this mysterious code and built a table. Now, the left panel indicates that you’re in the xfd database, which has a table called Contact.After you define a table, you can add ...

  • Page 706

    Implementing a Database with phpMyAdmin678 Figure 1-23: Adding a record to the table. After you add the record, choose Insert Another Row and click the Go button. Repeat until you’ve added all the contacts you want in your database.After you add all the records you want to the database, you ca...

  • Page 707

    Chapter 2: Managing Data with MySQLIn This Chapter✓ Working with SQL script files✓ Using AUTO_INCREMENT to build primary key values✓ Selecting a subset of fields✓ Displaying a subset of records✓ Modifying your data✓ Deleting records✓ Exporting your dataA lthough we tend to think of...

  • Page 708

    Writing SQL Code by Hand680 ✦ SQL scripts are portable. Moving an entire data structure to a new server is difficult, but if you have a script that creates and populates the database, that script is just an ASCII file. You can easily move a complete database (including the data) to a new machin...

  • Page 709

    Book VI Chapter 2Managing Data with MySQLWriting SQL Code by Hand681 (1, 'Steve Jobs', 'Apple', 'steve@rememberNewton.com');INSERT INTO contact VALUES (2, 'Linus Torvalds', 'Linux Foundation', 'linus@gnuWho.org');INSERT INTO contact VALUES (3, 'Andy Harris', 'Wiley Press', 'andy@aharrisBook...

  • Page 710

    Writing SQL Code by Hand682Creating a table involves several smaller tasks: 1. Specify the table name. The CREATE TABLE statement requires a table name. Specify the table name. Table names (like variables and filenames) should generally not contain spaces or punctuation without good reason. 2. B...

  • Page 711

    Book VI Chapter 2Managing Data with MySQLRunning a Script with phpMyAdmin683 1. Begin with the INSERT keyword. Use INSERT to clarify that this instruction is a data insertion command. 2. Specify the table you want to add data to. In my example, I have only one table, so use INTO contact to spe...

  • Page 712

    Running a Script with phpMyAdmin684To run a script in phpMyAdmin, follow these steps: 1. Connect to phpMyAdmin. Be sure that you’re logged in and connected to the system. 2. Navigate to the correct database. Typically, you use a drop-down list to the left of the main screen to pick the databa...

  • Page 713

    Book VI Chapter 2Managing Data with MySQLRunning a Script with phpMyAdmin685 4. (Optional) Type your SQL code directly into this dialog box. This shortcut is good for making quick queries about your data, but gen-erally you create and initialize data with prewritten scripts. 5. Move to the Impo...

  • Page 714

    Using AUTO_INCREMENT for Primary Keys686 Figure 2-4: Here’s the script results, shown in php­MyAdmin. Using AUTO_INCREMENT for Primary KeysPrimary keys are important because you use them as a standard index for the table. The job of a primary key is to uniquely identify each record in the tab...

  • Page 715

    Book VI Chapter 2Managing Data with MySQLUsing AUTO_INCREMENT for Primary Keys687 contactID int PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50), company VARCHAR(30), email VARCHAR(50)); INSERT INTO contact VALUES (null, 'Bill Gates', 'Microsoft', 'bill@msBob.com');INSERT INTO contact VALUES ...

  • Page 716

    Selecting Data from Your Tables688Selecting Data from Your TablesCreating a database is great, but the real point of a database is to extract information from it. SQL provides an incredibly powerful command for retrieving data from the database. The basic form looks as follows:SELECT * FROM co...

  • Page 717

    Book VI Chapter 2Managing Data with MySQLSelecting Data from Your Tables689 Figure 2-6: The standard SELECT statement returns the entire table. Selecting only a few fieldsAs databases get more complex, you’ll often find that you don’t want every-thing. Sometimes, you only want to see a few ...

  • Page 718

    Selecting Data from Your Tables690Here’s another really nice trick you can do with fields. You can give each column a new virtual field name:SELECT name as 'Person', email as 'Address'FROM contact;This code also selects only two columns, but this time, it attaches the special labels Person and...

  • Page 719

    Book VI Chapter 2Managing Data with MySQLSelecting Data from Your Tables691 ✦ A WHERE clause appears. The WHERE clause allows you to specify a condition. ✦ It has a condition. SQL supports conditions, much like ordinary program-ming languages. MySQL returns only the records that match this ...

  • Page 720

    Selecting Data from Your Tables692Searching with partial informationOf course, sometimes all you have is partial information. Take a look at the following variation to see how it works:SELECT * FROM contactWHERE company LIKE 'W%';This query looks at the company field and returns any records with...

  • Page 721

    Book VI Chapter 2Managing Data with MySQLSelecting Data from Your Tables693Searching for the ending value of a fieldLikewise, you can find fields that end with a particular value. Say that you want to send an e-mail to everyone in your contact book with a .com address. This query does the trick:...

  • Page 722

    Selecting Data from Your Tables694 Figure 2-12: This query searched for the phrase “book” anywhere in the e­mail string. Searching with regular expressionsIf you know how to use regular expressions, you know how great they can be when you need a more involved search. MySQL has a special for...

  • Page 723

    Book VI Chapter 2Managing Data with MySQLSelecting Data from Your Tables695Sorting your responsesYou can specify the order of your query results with the ORDER BY clause. It works like this:SELECT * FROM contactORDER BY email;The ORDER BY directive allows you to specify a field to sort by. In th...

  • Page 724

    Editing Records696By default, records are sorted in ascending order. Numeric fields are sorted from smallest to largest, and text fields are sorted in standard alphabetic order. Well, not quite standard alphabetic order . . . . SQL isn’t as smart as a librar-ian, who has special rules about ski...

  • Page 725

    Book VI Chapter 2Managing Data with MySQLExporting Your Data and Structure697More than one person in your database may be named Bill Gates. Names aren’t guaranteed to be unique, so they aren’t really the best search criteria. This situation is actually a very good reason to use primary keys....

  • Page 726

    Exporting Your Data and Structure698 ✦ You want to document the table structure. The structure of a data set is extremely important when you start writing programs using that struc-ture. Having the table structure available in a word-processing or PDF format can be very useful.MySQL (and thus p...

  • Page 727

    Book VI Chapter 2Managing Data with MySQLExporting Your Data and Structure699 The CSV format often uses commas and quotes, so if these characters appear in your data, you may encounter problems. Be sure to test your data and use some of the other delimiters if you have problems. ✦ MS Excel and...

  • Page 728

    Exporting Your Data and Structure700 ✦ Word-processing formats: Several formats are available to create docu-mentation for your project. Figure 2-18 shows a document created with this feature. Typically, you use these formats to describe the format of the data and the current contents. LaTeX a...

  • Page 729

    Book VI Chapter 2Managing Data with MySQLExporting Your Data and Structure701The resulting code is as follows:-- phpMyAdmin SQL Dump -- version 3.3.9 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jul 10, 2013 at 08:30 PM -- Server version: 5.5.8 ...

  • Page 730

    Exporting Your Data and Structure702server. You can then export the script for building the SQL file and load it into the second server.Creating XML dataOne more approach to saving data is through XML. phpMyAdmin creates a standard form of XML encapsulating the data. The XML output looks like thi...

  • Page 731

    Book VI Chapter 2Managing Data with MySQLExporting Your Data and Structure703 <column name="email">linus@gnuWho.org</column> </table> <table name="contact"> <column name="contactID">4</column> ...

  • Page 732

    704 Book VI: Managing Data with MySQLwww.freepdf-books.com

  • Page 733

    Chapter 3: Normalizing Your DataIn This Chapter✓ Understanding why single-table databases are inadequate✓ Recognizing common data anomalies✓ Creating entity-relationship diagrams✓ Using MySQL Workbench to create data diagrams✓ Understanding the first three normal forms✓ Defining data ...

  • Page 734

    Recognizing Problems with Single-Table Data706Table 3-1 A Sample DatabaseNamePowersVillainPlotMissionAgeThe PlumberSewer snake of doom, unclog­ging, ability to withstand smellsSeptic Slime MasterOvercome Chicago with slimeStop the Septic Slime37Binary BoyHexidecimation beam, obfuscationOctalEl...

  • Page 735

    Book VI Chapter 3Normalizing Your DataRecognizing Problems with Single-Table Data707 ✦ One large text field: That’s what I did in this case. I built a massive (255 character) VARCHAR field and hoped it would be enough. The user just has to type all the possible skills. ✦ Multiple fields: So...

  • Page 736

    Recognizing Problems with Single-Table Data708 Another so-called solution you sometimes see is to have a whole bunch of Boolean fields: Invisibility, Super-speed, X-ray vision, and so on. This fix solves part of the problem because Boolean data is small. It’s still trouble-some, though, because...

  • Page 737

    Book VI Chapter 3Normalizing Your DataIntroducing Entity-Relationship Diagrams709Fields with changeable dataAnother kind of problem is evident in the Age field. (See, even superheroes have a mandatory retirement age.) Age is a good example of a field that shouldn’t really be in a database becau...

  • Page 738

    Introducing Entity-Relationship Diagrams710is called MySQL Workbench actionURI(http://dev.mysql.com/downloads/tools/):(http://dev.mysql.com/downloads/actionURI(http://dev.mysql.com/downloads/tools/):tools/). This software has a number of really handy features: ✦ Visual representation of databas...

  • Page 739

    Book VI Chapter 3Normalizing Your DataIntroducing Entity-Relationship Diagrams711you to change the table name. You see a new table form like the one in Figure 3-2. Change the table name to hero but leave the other values blank for now. Figure 3-2: Now your model has a table in it. 3. Edit the ...

  • Page 740

    Introducing Entity-Relationship Diagrams712 4. Make a diagram of the table. So far, MySQL Workbench seems a lot like phpMyAdmin. The most useful feature of Workbench is the way it lets you view your tables in diagram form. You can view tables in a couple of ways, but the easiest way is to select...

  • Page 741

    Book VI Chapter 3Normalizing Your DataIntroducing Normalization713 ✦ Default NULL values are indicated: Most fields are defined with a default value of NULL. (Of course, the primary key can’t be NULL, and it’s defined that way.) ✦ Field and table names are quoted: The auto-generated code ...

  • Page 742

    Introducing Normalization714First normal formThe official definitions of the normal forms sound like the offspring of a lawyer and a mathematician. Here’s an official definition of the first normal form:A table is in first normal form if and only if it represents a relation. It does not allow n...

  • Page 743

    Book VI Chapter 3Normalizing Your DataIntroducing Normalization715A couple of things happen here: 1. Make a new table called power. This table contains nothing but a key and the power name. 2. Take the power field away from the hero table. The hero table no longer has a power field. 3. Add a pr...

  • Page 744

    Introducing Normalization716 Figure 3-6: Now I have three tables: hero, power, and mission. Third normal formThe third normal form adds one more requirement. Here is the official definition:A table is in 3NF if it is in 2NF and has no transitive dependencies on the candidate key.Wow! These defi...

  • Page 745

    Book VI Chapter 3Normalizing Your DataIdentifying Relationships in Your Data717Identifying Relationships in Your DataAfter you normalize the data (see the preceding section), you’ve created the entities (tables). Now, you need to investigate the relationships among these entities.Three main typ...

  • Page 746

    Identifying Relationships in Your Data718 Note that MySQL Workbench doesn’t actually allow you to draw many-to-many joins. I drew that into Figure 3-7 to illustrate the point. In the next chapter, I show how to emulate many-to-many relationships with a special trick called a link table.ER diag...

  • Page 747

    Chapter 4: Putting Data Together with JoinsIn This Chapter✓ Using SQL functions✓ Creating calculated fields✓ Working with date values✓ Building views✓ Creating inner joins and link tablesS ingle tables aren’t sufficient for most data. If you understand the rules of data normalization...

  • Page 748

    Calculating Virtual Fields720Begin by looking over the improved hero table in Figure 4-1. Figure 4-1: The hero table after normal­ization. The original idea for the database, introduced in Table 3-1 in Chapter 3 of this minibook, was to keep track of each hero’s age. This idea was bad becaus...

  • Page 749

    Book VI Chapter 4Putting Data Together with JoinsCalculating Date Values721FunctionDescriptionHOUR(), MINUTE(), SECOND()Extracts the particular value from a time value.DATEDIFF(A, B)Frequently used to find the time difference between two events (age).SUBTIMES(A, B)Determines the difference betwee...

  • Page 750

    Calculating Date Values722Begin by looking at a simple function that tells you the current date and time, as I do in Figure 4-2. Figure 4-2: The NOW() function returns the current date and time. The current date and time by themselves aren’t that important, but you can combine this informatio...

  • Page 751

    Book VI Chapter 4Putting Data Together with JoinsCalculating Date Values723This query calculates the difference between the current date, NOW(), and each hero’s birthday. The DATEDIFF() function works by converting both dates into integers. It can then subtract the two integers, giving you the ...

  • Page 752

    Calculating Date Values724(For more on this function, see the section “Using DATEDIFF to determine age,” earlier in this chapter.)Figure 4-5 is another version of a query that expresses age in terms of years and months. Figure 4-5: The age is now converted back to a date. This query takes t...

  • Page 753

    Book VI Chapter 4Putting Data Together with JoinsCalculating Date Values725 Figure 4-6: The YEAR(), MONTH(), and DAY() functions return parts of a date. The query is beginning to look complex, but it’s producing some really nice output. Still, it’s kind of awkward to have separate fields for...

  • Page 754

    Creating a View726This query uses the CONCAT() function to combine calculations and literal values to make exactly the output the user is expecting. Even though the birthday is the stored value, the output can be the age.Creating a ViewThe query that converts a birthday into a formatted age is ad...

  • Page 755

    Book VI Chapter 4Putting Data Together with JoinsCreating a View727 Figure 4-8: This simple query hides a lot of complexity. This code doesn’t look really fancy, but look at the output. It’s just like you had a table with all the information you wanted, but now the data is guaran-teed to be ...

  • Page 756

    Using an Inner Join to Combine Tables728Views are so great that it’s hard to imagine working with data without them. However, your hosting service may not have MySQL 5.0 or later installed, which means you aren’t able to use views. All is not lost. You can handle this issue in two ways.The mo...

  • Page 757

    Book VI Chapter 4Putting Data Together with JoinsUsing an Inner Join to Combine Tables729Foreign keys are used to reconnect tables that have been broken apart by normalization.Look at the mission table in Figure 4-10, and the relationship between the mission and hero tables begins to make sense....

  • Page 758

    Using an Inner Join to Combine Tables730 Figure 4-11: This query joins both tables, but it doesn’t seem right. You don’t really want all these values to appear; you want to see only the ones where the hero table’s missionID matches up to the missionID field in the mission table. In other w...

  • Page 759

    Book VI Chapter 4Putting Data Together with JoinsUsing an Inner Join to Combine Tables731This particular setup (using a foreign key reference to join up two tables) is called an inner join. Sometimes, you see the syntax likeSELECT hero.name AS 'hero', hero.missionID AS 'heroMID', mission.missi...

  • Page 760

    Using an Inner Join to Combine Tables732heroes, so if you try to link missions to heroes, you have listed fields in the mission table, violating the first normal form. (For information on the types of normal forms, see Chapter 3 of this minibook.) Figure 4-13 shows how it works in action. The re...

  • Page 761

    Book VI Chapter 4Putting Data Together with JoinsManaging Many-to-Many Joins733 ✦ Searching is much more efficient. Because the data is stored only one time, you no longer have to worry about spelling and typing errors. If the entry is wrong, it is universally wrong, and you can repair it in on...

  • Page 762

    Managing Many-to-Many Joins734 Figure 4-14: The hero table has no reference to powers. The inner join was easy because you just put a foreign key reference to the one side of the relationship in the many table. (See the section “Using an Inner Join to Combine Tables,” earlier in this chapter...

  • Page 763

    Book VI Chapter 4Putting Data Together with JoinsManaging Many-to-Many Joins735Here’s the tricky part. Take a look at a new table in Figure 4-16. Figure 4-16: This new table contains only foreign keys! The results of this query may surprise you. The new table contains nothing but foreign keys...

  • Page 764

    Managing Many-to-Many Joins736Using link tables to make many-to-many joinsFigure 4-17 displays a full-blown ER diagram of the hero data. Figure 4-17: Here’s the ER diagram of the hero data. Link tables aren’t really useful on their own because they contain no actual data. Generally, you use...

  • Page 765

    Book VI Chapter 4Putting Data Together with JoinsManaging Many-to-Many Joins737Figure 4-18 shows the result of this query. Now you have results you can use. Figure 4-18: The Link Query joins up heroes and powers. Once again, this query is an obvious place for a view:CREATE VIEW heroPowerView A...

  • Page 766

    Managing Many-to-Many Joins738The code is standard PHP data access, except it makes two passes to the database:<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>showDetails.php</title> <style type = "text/css&quo...

  • Page 767

    Book VI Chapter 4Putting Data Together with JoinsManaging Many-to-Many Joins739FROM heroPowerView WHERE hero = '$hero'HERE; //put powers in an unordered list $result = $con->query($query); print " <ul> \n"; foreach ($result as $row){ foreach ($row as $...

  • Page 768

    740 Book VI: Managing Data with MySQLwww.freepdf-books.com

  • Page 769

    Chapter 5: Connecting PHP to a MySQL DatabaseIn This Chapter✓ Building the connection string✓ Sending queries to a database✓ Retrieving data results✓ Formatting data output✓ Allowing user queries✓ Cleaning user-submitted data requestsD ata has become the prominent feature of the web. ...

  • Page 770

    PHP and MySQL: A Perfect (but Geeky) Romance742costing thousands of dollars. (And it is better than many that cost hun-dreds of dollars.) ✦ PHP has built-in support for MySQL. PHP includes a number of func-tions specifically designed to help programmers maintain MySQL databases. ✦ You probab...

  • Page 771

    Book VI Chapter 5Connecting PHP to a MySQL DatabasePHP and MySQL: A Perfect (but Geeky) Romance743As an example, take a look at contact.php in Figure 5-1. Figure 5-1: This program gets all the contact data from a database. The contact.php program contains none of the actual contact information....

  • Page 772

    PHP and MySQL: A Perfect (but Geeky) Romance744 If you want to try this program at home, begin by running the build ContactAutoIncrement.sql script (available in Book VI, Chapter 2) in your copy of MySQL. Note that you’ll probably have to change the database, username, and password values to m...

  • Page 773

    Book VI Chapter 5Connecting PHP to a MySQL DatabasePHP and MySQL: A Perfect (but Geeky) Romance745Introducing PDOPHP has used a number of mechanisms for connecting to databases over the years. For a long time, the standard was a series of libraries for the various database types. Many people used...

  • Page 774

    PHP and MySQL: A Perfect (but Geeky) Romance746 2. Build a new PDO object. Because PDO is object-oriented, use the new keyword to call the PDO object constructor. (See Book V, Chapter 7 for more on objects and con-structors in PHP.)$con = new PDO('mysql:host=localhost;dbname=dbname', "usern...

  • Page 775

    Book VI Chapter 5Connecting PHP to a MySQL DatabasePHP and MySQL: A Perfect (but Geeky) Romance747Retrieving data from the databaseAfter a PDO connection is set up, it’s pretty easy to use. Here’s the overall plan for retrieving data from the PDO connection: 1. Put all PDO code in an exceptio...

  • Page 776

    PHP and MySQL: A Perfect (but Geeky) Romance748 7. Each row is an associative array. Each row can also be thought of as an array. PDO has a number of ways to extract the data, but you set the fetch mode to associative array in Step 5. This means you can use the associative variant of the foreach...

  • Page 777

    Book VI Chapter 5Connecting PHP to a MySQL DatabasePHP and MySQL: A Perfect (but Geeky) Romance749<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>contact.php</title> <style type = "text/css&quo...

  • Page 778

    PHP and MySQL: A Perfect (but Geeky) Romance750 print " </tr> \n"; } // end record loop print "</table> \n"; } catch(PDOException $e) { echo 'ERROR: ' . $e->getMessage(); } // end try ?> </p> </body&...

  • Page 779

    Book VI Chapter 5Connecting PHP to a MySQL DatabaseAllowing User Interaction751 $result = $con->query($query); //return only the first row (we only need field names)) $row = $result->fetch(PDO::FETCH_ASSOC); The fetch method pulls the next available record from the $re...

  • Page 780

    Allowing User Interaction752 Figure 5-3: The user can check for any value in any field. Here are a couple of interesting things about the form in Figure 5-3: ✦ The search value can be anything. The first field is an ordinary text field. The user can type absolutely anything here, so you shoul...

  • Page 781

    Book VI Chapter 5Connecting PHP to a MySQL DatabaseAllowing User Interaction753Building an HTML search formThis is what the HTML code for search.html looks like:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>s...

  • Page 782

    Allowing User Interaction754 Figure 5-4: The program searches the database according to the parameters in search.html. Never directly interpolate user input into an SQL statement. Use the sanitiz-ing mechanisms described in the next section instead.You can use input data to build custom queries...

  • Page 783

    Book VI Chapter 5Connecting PHP to a MySQL DatabaseAllowing User Interaction755 The database will compile the statement as-is, but will not execute it yet. The question marks indicate values that will be provided later, and you can have as many as you wish. 3. Execute the prepared statement. Wh...

  • Page 784

    Allowing User Interaction756 $result = $stmt->fetchAll(PDO::FETCH_ASSOC); if (empty($result)){ print "No matches found"; } else { foreach($result as $row){ foreach ($row as $field => $value){ print &quo...

  • Page 785

    Book VI Chapter 5Connecting PHP to a MySQL DatabaseAllowing User Interaction757 if (in_array($srchField, $fieldName)){ .. } else { print "That is not a valid field name"; } // end if 5. Create variables for $field and $value. The $field value is copied dir...

  • Page 786

    Allowing User Interaction758You can use the same general techniques to control all SQL statements needed to create and modify a database. In fact, this is exactly how most data programs work on the Internet, maintaining databases and allowing the user to indirectly modify the data.If you’ve bee...

  • Page 787

    actionURI(http://www.dummies.com/extras/html5css3aio):Visit actionURI(http://www.dummies.com/extras/html5css3aio):www.dummies.com/extras/html5css3aioactionURI(http://www.dummies.com/extras/html5css3aio): for more on fun with jQuery plug-ins.Part VIIIntegrating the Client and Server with AJAXwww....

  • Page 788

    Contents at a Glance Contents at a GlanceChapter 1: AJAX Essentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .761AJAX Spelled Out .............................................................................................................762Making a Basic AJAX Connect...

  • Page 789

    Chapter 1: AJAX EssentialsIn This Chapter✓ Understanding AJAX✓ Using JavaScript to manage HTTP requests✓ Creating an XMLHttpRequest object✓ Building a synchronous AJAX request✓ Retrieving data from an AJAX request✓ Managing asynchronous AJAX requestsI f you’ve been following web tre...

  • Page 790

    AJAX Spelled Out762knowledge of each other. AJAX helps these two types of programming work together better. ✦ A series of libraries that facilitate this communication: AJAX isn’t that hard, but it does have a lot of details. Several great libraries have sprung up to simplify using AJAX techno...

  • Page 791

    Book VII Chapter 1AJAX EssentialsAJAX Spelled Out763many computing acronyms, it may be fun to say, but it doesn’t really mean much. AJAX stands for Asynchronous JavaScript And XML. Truthfully, these terms were probably chosen to make a pronounceable acronym rather than for their accuracy or re...

  • Page 792

    Making a Basic AJAX Connection764 ✦ Plain old text: Sometimes you just want to grab some text from the server. Maybe you have a text file with a daily quote in it or something. ✦ Formatted HTML: You can have text stored on the server as a snippet of HTML/XHTML code and use AJAX to load this p...

  • Page 793

    Book VII Chapter 1AJAX EssentialsMaking a Basic AJAX Connection765When the user clicks the link, the small pop-up shown in Figure 1-2 appears. Figure 1-2: This text came from the server. If you don’t get the joke, you need to go rent Monty Python and the Holy Grail. It’s part of the geek ...

  • Page 794

    Making a Basic AJAX Connection766Look over the following code, and you’ll find it reasonable enough:<!DOCTYPE HTML><html lang="en";><head> <meta charset="UTF-8"> <title>basicAJAX.html</title> <script type = "text/javascript"...

  • Page 795

    Book VII Chapter 1AJAX EssentialsMaking a Basic AJAX Connection767All you really need is some kind of structure that can trigger a JavaScript function. AJAX isn’t a complex technology, but it does draw on several other technolo-gies. You may need to look over the JavaScript chapters in Book IV...

  • Page 796

    Making a Basic AJAX Connection768statusReturns the HTTP status code returned by the server (200 is success).Check for error codes (“window closed,” “bal-loon popped,” “string broken,” or “everything’s great”).statusTextText form of HTTP status.Text form of status code.responseTe...

  • Page 797

    Book VII Chapter 1AJAX EssentialsMaking a Basic AJAX Connection769me here.) The synchronous form is easier to understand, so I use it first. The next example (and all the others in this book) uses the asynchro-nous approach.For this example, I use the GET mechanism to load a file called beast.tx...

  • Page 798

    Making a Basic AJAX Connection770Just like the post office stamping success/error messages on your envelope, the server sends back status messages with your request. You can see all the possible status codes on the World Wide Web Consortium’s website at actionURI(http://www.w3.org/Protocols/rfc...

  • Page 799

    Book VII Chapter 1AJAX EssentialsAll Together Now — Making the Connection Asynchronous771formatted data (XML or JSON) that I can manipulate with JavaScript and do whatever I want with.All Together Now — Making the Connection AsynchronousThe synchronous AJAX connection described in the previo...

  • Page 800

    All Together Now — Making the Connection Asynchronous772 alert(request.responseText); } // end if } // end if } // end checkData </script></head><body><h1>Asynchronous AJAX transmission</h1><form action = ""> <p> <butto...

  • Page 801

    Book VII Chapter 1AJAX EssentialsAll Together Now — Making the Connection Asynchronous773 3. Assign an event handler to catch responses. You can use event handlers much like the ones in the DOM. In this particular case, I’m telling the request object to call a function called checkData when...

  • Page 802

    All Together Now — Making the Connection Asynchronous774The basic strategy for checking a response is to check the ready state in the aptly named request.readyState property. If the ready state is 4, check the status code to ensure that no error exists. If the ready state is 4 and the status is...

  • Page 803

    Chapter 2: Improving JavaScript and AJAX with jQueryIn This Chapter✓ Downloading and including the jQuery library✓ Making an AJAX request with jQuery✓ Using component selectors✓ Adding events to components✓ Creating a simple content management system with jQueryJ avaScript has amazing c...

  • Page 804

    Introducing jQuery776 ✦ Prototype: One of the first AJAX libraries to become popular. It includes great support for AJAX and extensions for user interface objects (through the scriptaculous extension). ✦ Yahoo User Interface (YUI): This is used by Yahoo! for all its AJAX appli-cations. Yahoo!...

  • Page 805

    Book VII Chapter 2Improving JavaScript and AJAX with jQueryIntroducing jQuery777 ✦ It’s free and open source. It’s available under an open-source license, which means it costs nothing to use, and you can look it over and change it if you wish. ✦ It’s reasonably typical. If you choose to...

  • Page 806

    Your First jQuery App778 ✦ The library is automatically updated. You always have access to the latest version of the library without making any changes to your code. ✦ The library may load faster. The first time one of your pages reads the library from Google’s servers, you have to wait for...

  • Page 807

    Book VII Chapter 2Improving JavaScript and AJAX with jQueryYour First jQuery App779 Figure 2-1: The content of this page is modified with jQuery. Setting up the pageAt first, the jQuery app doesn’t look much different than any other HTML/JavaScript code you’ve already written, but the JavaSc...

  • Page 808

    Your First jQuery App780The basic features of changeme.html are utterly unsurprising: ✦ The HTML has a div named output. This div initially says, “Did this change?” The code should change the content to something else. ✦ The HTML calls a function called changeMe()when the body finishes lo...

  • Page 809

    Book VII Chapter 2Improving JavaScript and AJAX with jQueryCreating an Initialization Function781The jQuery approach is a little cleaner, and it doesn’t get a reference to a DOM object (as the getElementById technique does), but it makes a new jQuery object that is based on the DOM element. Don...

  • Page 810

    Creating an Initialization Function782Using $(document).ready()jQuery has a great alternative to body onload that overcomes these short-comings. Take a look at the code for ready.html to see how it works:<!DOCTYPE html><html lang = "en-US"> <head> <title>ready....

  • Page 811

    Book VII Chapter 2Improving JavaScript and AJAX with jQueryInvestigating the jQuery Object783 You see several other places (particularly in event handling) where jQuery expects a function as a parameter. Such a function is frequently referred to as a callback function because it’s called after ...

  • Page 812

    Investigating the jQuery Object784 Figure 2-2: All the styles here are applied dynamically by jQuery functions. The code displays a terseness common to jQuery code:<!DOCTYPE html> <title>styleElements.html</title> <meta charset="UTF-8"> <script type = &quo...

  • Page 813

    Book VII Chapter 2Improving JavaScript and AJAX with jQueryInvestigating the jQuery Object785 ✦ There’s a paragraph with the ID myParagraph. This will be used to illustrate how to target an element by ID. ✦ There are two elements with the class bordered. You have no easy way in ordinary DOM...

  • Page 814

    Adding Events to Objects786If you apply a style rule to a collection of objects (like all H1 objects or all objects with the bordered class), the same rule is instantly applied to all the objects.A more powerful variation of the style rule exists that allows you to apply several CSS styles at onc...

  • Page 815

    Book VII Chapter 2Improving JavaScript and AJAX with jQueryAdding Events to Objects787Adding a hover eventLook at the code to see how it works:<!DOCTYPE html><html lang="en"><head> <title>hover.html</title> <meta charset="UTF-8"> <scri...

  • Page 816

    Adding Events to Objects788 $("li").hover( function(){ $(this).css("border", "1px solid black"); }, function(){ $(this).css("border", "0px none black"); } );Note that this is still technical...

  • Page 817

    Book VII Chapter 2Improving JavaScript and AJAX with jQueryAdding Events to Objects789The code shows how easy this kind of feature is to add:<!DOCTYPE html><html lang="en"><head> <title>class.html</title> <meta charset="UTF-8"> <style...

  • Page 818

    Making an AJAX Request with jQuery790 jQuery has several methods for manipulating the class of an element: • addClass() assigns a class to the element.• removeClass() removes a class definition from an element.• toggleClass() switches the class (adds it if it isn’t currently attached or ...

  • Page 819

    Book VII Chapter 2Improving JavaScript and AJAX with jQueryMaking an AJAX Request with jQuery791Including a text file with AJAXThis program is very similar in function to the asynch.html program described in Chapter 1 of this minibook, but the code is much cleaner:<!DOCTYPE html><html la...

  • Page 820

    Making an AJAX Request with jQuery792As an example, take a look at cmsAJAX, shown in Figure 2-6. Figure 2-6: This page is created dynamically with AJAX and jQuery. Although nothing is all that shocking about the page from the user’s perspec-tive, a look at the code can show some surprises:<...

  • Page 821

    Book VII Chapter 2Improving JavaScript and AJAX with jQueryMaking an AJAX Request with jQuery793 <div class = "content" id = "content2"> </div> <!-- end content div --> <div id = "footer"> </div> <!-- end...

  • Page 822

    Making an AJAX Request with jQuery794The advantage of the template-style approach is code reuse. Just like the use of an external style allows you to multiply a style sheet across hundreds of documents, designing a template without content allows you to store code snippets in smaller files and re...

  • Page 823

    Chapter 3: Animating jQueryIn This Chapter✓ Hiding and showing elements with jQuery✓ Fading elements in and out✓ Adding a callback function to a transition✓ Element animation✓ Object chaining✓ Using selection filters✓ Adding and removing elementsT he jQuery library simplifies a lot ...

  • Page 824

    Playing Hide and Seek796The hideShow program looks simple at first, but it does some quite interest-ing things. All of the level-two headings are actually buttons, so when you click them, interesting things happen: ✦ The show button displays a previously hidden element. Figure 3-2 dem-onstrate...

  • Page 825

    Book VII Chapter 3Animating jQueryPlaying Hide and Seek797 ✦ The fade out button fades the element to the background color. This technique gradually modifies the opacity of the element so that it even-tually disappears.You can adjust how quickly the transition animation plays. You can specify e...

  • Page 826

    Playing Hide and Seek798 box-shadow: 5px 5px 5px gray; } </style> <script type = "text/javascript" src = "jquery-1.10.2.min.js"></script> <script type = "text/javascript"> $(init); function init(){ //styleContent()...

  • Page 827

    Book VII Chapter 3Animating jQueryPlaying Hide and Seek799Writing the HTML and CSS foundationThe HTML used in this example is minimal, as is common in jQuery development: ✦ A single level-one heading ✦ A series of level-two headings ✦ A paragraphThe level-two headings will be used as butto...

  • Page 828

    Playing Hide and Seek800Initializing the pageThe initialization sequence simply sets the stage and assigns a series of event handlers: $(init); function init(){ //styleContent(); $("#content").hide(); $("#show").click(showContent); $("#hide...

  • Page 829

    Book VII Chapter 3Animating jQueryPlaying Hide and Seek801The hide and show methods act instantly. If the element is currently visible, the show() method has no effect. Likewise, hide() has no effect on an ele-ment that’s already hidden.Toggling visibilityIn addition to hide() and show(), the j...

  • Page 830

    Changing Position with jQuery802Fading an element in and outA third type of “now you see it” animation is provided by the fade methods. These techniques adjust the opacity of the element. The code should look quite familiar by now: function fadeIn(){ $("#content").fadeIn(&qu...

  • Page 831

    Book VII Chapter 3Animating jQueryChanging Position with jQuery803 Figure 3-3: Click the buttons, and the element moves. <!DOCTYPE html><html lang = "en-US"> <head> <title>Animate.html</title> <meta charset="UTF-8"> <style type = &qu...

  • Page 832

    Changing Position with jQuery804 //move to initial spot $("#content").css("left", "50px") .css("top", "100px"); //slide to new spot $("#content").animate({ "left": "400px", "...

  • Page 833

    Book VII Chapter 3Animating jQueryChanging Position with jQuery805The buttons all have id attributes, but I didn’t attach functions to them with the onclick attribute. After you’re using jQuery, it makes sense to commit to a jQuery approach and use the jQuery event techniques. The only other ...

  • Page 834

    Changing Position with jQuery806not only changes the text of the content node but also makes a new node. You can attach that node to a variable like this if you want: var newNode = $("#content").text("changed");However, what most jQuery programmers do is simply attach new...

  • Page 835

    Book VII Chapter 3Animating jQueryChanging Position with jQuery807specified span of time. The glide button on animate.html smoothly moves the content div from (50, 100) to (400, 200) over two seconds: function glide(){ //move to initial spot $("#content").css("left&qu...

  • Page 836

    Modifying Elements on the Fly808Move a little bit: Relative motionYou can also use the animation mechanism to move an object relative to its current position. The arrow buttons and their associated functions perform this task: function left(){ $("#content").animate({"left&q...

  • Page 837

    Book VII Chapter 3Animating jQueryModifying Elements on the Fly809 Figure 3-4: The default state of change- Content is a little dull. Of course, the buttons allow the user to make changes to the page dynami-cally. Clicking the Add Text button adds more text to the content area, as you can see in...

  • Page 838

    Modifying Elements on the Fly810 Figure 3-6: I’ve made several clones of the original content. ✦ The Wrap in Div button lets you wrap an HTML element around any existing element. The Wrap in Div button puts a div (with a red border) around every cloned element. You can click this button mul...

  • Page 839

    Book VII Chapter 3Animating jQueryModifying Elements on the Fly811code that turns all odd-numbered paragraphs into white text with a green background. Look at Figure 3-8 for a demonstration. Figure 3-8: All odd-numbered paragraphs have a new style. ✦ The Reset button resets all the changes y...

  • Page 840

    Modifying Elements on the Fly812 $("#addText").click(addText); $("#wrap").click(wrap); $("#clone").click(clone); $("#oddGreen").click(oddGreen); } // end init function reset(){ //remove all but the original content ...

  • Page 841

    Book VII Chapter 3Animating jQueryModifying Elements on the Fly813Admittedly you see a lot of code here, but when you consider how much functionality this page has, it really isn’t too bad. Look at it in smaller pieces, and it all makes sense.Building the basic pageAs usual, begin by inspecting...

  • Page 842

    Modifying Elements on the Fly814Table 3-1 Methods That Add Text to a NodeMethodDescriptionappend(text)Adds the text (or HTML) to the end of the selected element(s)prepend(text)Adds the content at the beginning of the selected element(s)insertAfter(text)Adds the text after the selected element (o...

  • Page 843

    Book VII Chapter 3Animating jQueryModifying Elements on the Fly815 1. Select the first paragraph. The first paragraph is the one I want to copy. (In the beginning, only one exists, but that will change soon.) 2. Use the clone()method to make a copy. Now you’ve made a copy, but it still isn’...

  • Page 844

    Modifying Elements on the Fly816all cloned paragraphs with red borders. This would be a very tedious effect to achieve in ordinary DOM and JavaScript, but jQuery makes it pretty easy to do: function wrap(){ $("p:gt(0)").wrap("<div></div>"); } // end wrapThe wrap() ...

  • Page 845

    Book VII Chapter 3Animating jQueryModifying Elements on the Fly817 function reset(){ //remove all but the original content $("p:gt(0)").remove(); $("div:not(#content)").remove(); //reset the text of the original content $("#content").html("<p>Th...

  • Page 846

    818 Book VII: Integrating the Client and Server with AJAXwww.freepdf-books.com

  • Page 847

    Chapter 4: Using the jQuery User Interface ToolkitIn This Chapter✓ Exploring the jQuery UI✓ Installing the UI and templates✓ Using UI template classes✓ Dragging and dropping✓ Binding events✓ Resizing elementsT he jQuery library is an incredible tool for simplifying JavaScript progra...

  • Page 848

    What the jQuery User Interface Brings to the Table820 ✦ A complete icon library: The jQuery UI has a library of icons for use in your web development. It has arrows, buttons, and plenty of other doo-dads that can be easily changed to fit your template. ✦ A very clean, modern look: It’s very...

  • Page 849

    Book VII Chapter 4Using the jQuery User Interface ToolkitWhat the jQuery User Interface Brings to the Table821Before you use themeRoller to change themes, use it to get acquainted with the UI elements. Several useful tools are visible in Figure 4-1: ✦ Accordion: The upper-middle segment of the...

  • Page 850

    What the jQuery User Interface Brings to the Table822 ✦ Dialog: The open dialog button pops up what appears to be a dialog box. It acts much like the JavaScript alert, but it’s much nicer looking, and it has features that make it much more advanced. In Figure 4-2, the dialog box has a clever...

  • Page 851

    Book VII Chapter 4Using the jQuery User Interface ToolkitWhat the jQuery User Interface Brings to the Table823The built-in themes are pretty impressive, but of course, you can make your own. Although you’re always free to edit the CSS manually, the whole point of the themeRoller application is ...

  • Page 852

    What the jQuery User Interface Brings to the Table824<!DOCTYPE html><html lang = "en"> <head> <title>drag.html</title> <meta charset= "UTF-8" /> <style type = "text/css"> #dragMe { width: 100px; height: 100px; ...

  • Page 853

    Book VII Chapter 4Using the jQuery User Interface ToolkitWhat the jQuery User Interface Brings to the Table825 Previous versions of jQuery UI allowed you to download the entire package but stored each of the various elements in a separate JavaScript file. It was common to have a half-dozen differ...

  • Page 854

    What the jQuery User Interface Brings to the Table826 8. Link to the JavaScript files. The jQuery UI toolkit also installs two JavaScript files: the standard jQuery library and the jQuery UI library. By default, both of these files are installed in the js directory. You’ll need to link to both...

  • Page 855

    Book VII Chapter 4Using the jQuery User Interface ToolkitResizing on a Theme827 If you’re really paying attention, you might notice that the jQuery version that came with the UI is slightly older than the 10.2 version I used in the previous chapter. Really, it’s not a big deal because the di...

  • Page 856

    Resizing on a Theme828Figure 4-6 shows the page after the resize me element has changed sizes, and you can see that the rest of the page reformats itself to fit the newly resized element. Figure 4-6: When the element is resized, the rest of the page adjusts. The following code reveals that most...

  • Page 857

    Book VII Chapter 4Using the jQuery User Interface ToolkitResizing on a Theme829 $(init); function init(){ $("#resizeMe").resizable(); themify(); } // end init function themify(){ //add theme-based CSS to the elements $("div").addClass(...

  • Page 858

    Resizing on a Theme830 ✦ The jQuery UI library: This file is also a standard JavaScript library. Earlier in this chapter, I describe how to obtain a custom version of this file. ✦ The theme CSS file: When you create a theme with themeRoller, you are provided with a CSS file. This file is your...

  • Page 859

    Book VII Chapter 4Using the jQuery User Interface ToolkitResizing on a Theme831 Themes are simply CSS classes. To apply a CSS theme to an element, you can just add a special class to the object.For example, you can make a paragraph look like the current definition of the ui-widget by adding this ...

  • Page 860

    Resizing on a Theme832 5. Make all headlines conform to the widget-header style. The jQuery themes include a nice headline style. You can easily make all heading tags (H1 to H6) follow this theme. Use the :header filter to identify all headings, and apply the ui-widget-header and ui- corner-all ...

  • Page 861

    Book VII Chapter 4Using the jQuery User Interface ToolkitResizing on a Theme833A few other classes are defined in UI themes, but these are the most commonly used. Refer to the current jQuery UI documentation for more details.Adding an iconNote the small start that appears inside the resizeMe ele...

  • Page 862

    Dragging, Dropping, and Calling Back834Or, you can use jQuery to add the appropriate code to your element:$("#myPara").append('<span class = "ui-icon ui-icon-star"></span>');Dragging, Dropping, and Calling BackjQuery elements look good, but they also have interesti...

  • Page 863

    Book VII Chapter 4Using the jQuery User Interface ToolkitDragging, Dropping, and Calling Back835 width: 100px; height: 100px; border: 1px solid blue; text-align: center; background-color: white; position: absolute; z-index: 100; } #target { width: 200px; height: 200px...

  • Page 864

    Dragging, Dropping, and Calling Back836 function cloneDragMe(){ for (i = 1; i <= 4; i++){ zValue = (101 + i) + ""; yPos = 100 + (i * 20) + "px"; $("div:first").clone() .insertAfter("div:last") .css("top"...

  • Page 865

    Book VII Chapter 4Using the jQuery User Interface ToolkitDragging, Dropping, and Calling Back837 cloneDragMe(); //make all drag me elements draggable $(".dragMe").draggable(); //set target as droppable $("#target").droppable(); //bind eve...

  • Page 866

    Dragging, Dropping, and Calling Back838Handling the dropWhen the user drags a dragMe element and drops it on the target, the tar-get’s background color changes and the program reports the text of the ele-ment that was dragged. The code is easy: function changeTarget(event, ui){ $("...

  • Page 867

    Book VII Chapter 4Using the jQuery User Interface ToolkitDragging, Dropping, and Calling Back839 function resetTarget(event, ui){ $("#target").removeClass("ui-state-highlight") .html("Drop on me"); } // end resetAll you have to do is this: 1. Remo...

  • Page 868

    Dragging, Dropping, and Calling Back840 2. Create a zValue for the element. The CSS zIndex property is used to indicate the overlapping of ele-ments. Higher values appear to be closer to the user. I give each element a zOrder of over 100 to ensure that it appears over the target. (If you don’t...

  • Page 869

    Chapter 5: Improving Usability with jQueryIn This Chapter✓ Working with scroll bars✓ Building a sorting mechanism✓ Managing selectable items✓ Using the dialog box tool✓ Creating an accordion page✓ Building a tab-based interfaceT he jQuery UI adds some really great capabilities to your...

  • Page 870

    Multi-Element Designs842 ✦ The tabs tool allows you to easily turn a large page into a page with a tab menu.These tools are incredibly easy to use, and they add tremendously to your page development options. Both of these tools automate and simplify the DOM and AJAX work it takes to build a l...

  • Page 871

    Book VII Chapter 5Improving Usability with jQueryMulti-Element Designs843The accordion effect is strikingly easy to achieve with jQuery:<!DOCTYPE html><html lang = "en-US"> <head> <title>accordion.html</title> <meta charset = "UTF-8" /> ...

  • Page 872

    Multi-Element Designs844 <h2><a href = "#">Book II - Styling with CSS</a></h2> <ol> <li>Coloring Your World</li> <li>Styling Text</li> <li>Selectors, Class, and Style</li> <li>Borders and Backgrounds&l...

  • Page 873

    Book VII Chapter 5Improving Usability with jQueryMulti-Element Designs845 6. Apply the accordion()method to the div. Use jQuery to identify the div that contains collapsible content and apply accordion() to it: function init(){ $("#accordion").accordion(); }Building a tabbed...

  • Page 874

    Multi-Element Designs846 Figure 5-4: Clicking a tab changes the main content and the appearance of the tabs. Like the accordion, the tab effect is incredibly easy to achieve. Look over the code:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF...

  • Page 875

    Book VII Chapter 5Improving Usability with jQueryMulti-Element Designs847 <li>Managing Information with Lists and Tables</li> <li>Making Connections with Links</li> <li>Adding Images</li> <li>Creating forms</li> </ol> &...

  • Page 876

    Multi-Element Designs848 6. Build an init()function as usual. Use the normal jQuery techniques. 7. Call the tabs()method on the main div. Incredibly, one line of jQuery code does all the work.Using tabs with AJAXYou have an even easier way to work with the jQuery tab interface. Rather than plac...

  • Page 877

    Book VII Chapter 5Improving Usability with jQueryImproving Usability849the first tab (chap1.html) and loads it into the display area. Here’s what book1.html contains: <h2>Book I - Creating the HTML Foundation</h2> <ol> <li>Sound HTML Foundations</li> ...

  • Page 878

    Improving Usability850A lot is going on in this page, but the tabbed interface really cleans it up and lets the user concentrate on one idea at a time. Using the tabbed interface can really simplify your user’s life.This page is a bit long because it has a number of sections. I demonstrate the ...

  • Page 879

    Book VII Chapter 5Improving Usability with jQueryImproving Usability851Playing the dating gameImagine that you’re writing a program that requires a birth date. Getting date information from the user can be an especially messy problem because so many variations exist. Users might use numbers for...

  • Page 880

    Improving Usability852 3. Isolate the text input element with jQuery. Build a standard jQuery node from the input element. 4. Add the datepicker()functionality. Use the datePicker() method to convert the text node into a date- picker. This is usually done in some type of init() function. The re...

  • Page 881

    Book VII Chapter 5Improving Usability with jQueryImproving Usability853The slider is (like many jQuery UI objects) very easy to set up. Here’s the relevant chunk of HTML code: <div id = "sliderTab"> <h2>slider</h2> <div id = "slider"><...

  • Page 882

    Improving Usability854Selectable elementsYou may have a situation where you want the user to choose from a list of ele-ments. The selectable widget is a great way to create this functionality from an ordinary list. The user can drag or Ctrl+click items to select them. Special CSS classes are auto...

  • Page 883

    Book VII Chapter 5Improving Usability with jQueryImproving Usability855 } #selectable .ui-selecting { background-color: gray; } #selectable .ui-selected { background-color: black; color: white; } </style> 3. In the init()function, specify the list as a ...

  • Page 884

    Improving Usability856The user can grab members of the list and change their order, as shown in Figure 5-10.Making a sortable list is really easy. Follow these steps: 1. Build a regular list. Sortable elements are usually lists. The list is a regular list, but with an ID: <div id = "...

  • Page 885

    Book VII Chapter 5Improving Usability with jQueryImproving Usability857 Figure 5-11: This dialog box is actually a jQuery UI node. Building the dialog box is not difficult, but you need to be able to turn it on and off with code, or it will not act like a proper dialog box (which mimics a windo...

  • Page 886

    Improving Usability858 4. Close the dialog box. To close a dialog box, refer to the dialog box node and call the dialog() method on it again. This time, send the single value “close” as a parameter, and the dialog box will immediately close: //initially close dialog $("#dialog...

  • Page 887

    Chapter 6: Working with AJAX DataIn This Chapter✓ Understanding the advantages of server-side programming✓ Getting to know PHP✓ Writing a form for standard PHP processing✓ Building virtual forms with AJAX✓ Submitting interactive AJAX requests✓ Working with XML data✓ Responding to J...

  • Page 888

    Sending Requests AJAX Style860but in this example the results of the PHP program are integrated directly onto the original HTML page. Begin by looking over the HTML/JavaScript code:<!DOCTYPE html><html lang = "en-US"> <head> <title>AJAXTest.html</title> ...

  • Page 889

    Book VII Chapter 6Working with AJAX DataSending Requests AJAX Style861Here’s how it works: 1. Begin with an HTML framework. As always, HTML forms the spine of any web program. The HTML here is quite simple — a heading and a div for output. Note that this example does not include a form. 2. I...

  • Page 890

    Sending Requests AJAX Style862nameForm.html and greetUser.php on the companion website to compare a more typical HTML/PHP solution. See this book’s Introduction for more on the website.) That’s a lot of overhead, building an entire HTML page every pass. A lot of material is repeated. However,...

  • Page 891

    Book VII Chapter 6Working with AJAX DataBuilding a Multipass Application863Building a Multipass Application The most common use of AJAX is to build an application that hides the rela-tionship between the client and the server. For example, look at the multiPass.html page shown in Figure 6-2. Thi...

  • Page 892

    Building a Multipass Application864It’s certainly possible to get this behavior from PHP alone, but it’s interest-ing to see an HTML/JavaScript page that can access data from a database. Of course, some PHP is happening, but AJAX manages the process. Take a look at the code for multiPass.html...

  • Page 893

    Book VII Chapter 6Working with AJAX DataBuilding a Multipass Application865 2. Build a simple form. The page has a form, but this form is designed more for client-side inter-action than server-side. Note that the form does not specify an action parameter. That’s because the form won’t be dir...

  • Page 894

    Building a Multipass Application866 4. Call loadList.php. When you call a PHP program, you won’t be loading in the text of the program. Instead, you’re asking that program to do whatever it does (in this case, get a list of hero names and heroIDs) and place the results of the program in the ...

  • Page 895

    Book VII Chapter 6Working with AJAX DataBuilding a Multipass Application867It should go to the database and find all the records in the hero table. It should then assign heroID to the value attribute of each option, and should display each hero’s name. After you know what you want to create, it...

  • Page 896

    Building a Multipass Application868If the user has selected a hero, you have the hero’s heroID as the value of the <select> object. You can use this data to bundle a request to a PHP program. That program uses the heroID to build a query and return data about the requested hero: 1. Extrac...

  • Page 897

    Book VII Chapter 6Working with AJAX DataBuilding a Multipass Application869 $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $con->prepare("SELECT * FROM hero WHERE heroID = ?"); $stmt->execute(array($heroID)); $re...

  • Page 898

    Working with XML Data870 5. Process the results. Use the ordinary foreach mechanism to print out the results of the query. You can get as fancy as you want with the output, but I’m going for a very standard “print all the contents” approach for now. foreach($result as $row){ ...

  • Page 899

    Book VII Chapter 6Working with AJAX DataWorking with XML Data871Review of XMLThe XML format has become an important tool for encapsulating data for transfer between the client and the server. You might already be familiar with XML because XHTML is simply HTML following the stricter XML standard....

  • Page 900

    Working with XML Data872 4. Add attributes as needed. You can add attributes to your XML elements just like the ones in HTML. As in HTML, attributes are name/value pairs separated by an equal sign (=), and the value must always be encased in quotes. 5. Nest elements as you do in HTML. Be carefu...

  • Page 901

    Book VII Chapter 6Working with AJAX DataWorking with XML Data873 function processResult(data, textStatus){ //clear the output $("#output").html(""); //find the pet nodes... $(data).find("pet").each(printPetName); } // end processResult ...

  • Page 902

    Working with XML Data874Retrieving the dataThe init() function sets up an AJAX request: $(init); function init(){ $.get("pets.xml", processResult); } // end initThis function uses the get() function to request data: 1. Use the jQuery get()mechanism to set up the request. ...

  • Page 903

    Book VII Chapter 6Working with AJAX DataWorking with XML Data875 3. Find each pet node. Use the find() method to identify the pet nodes within the data. 4. Specify a command to operate on each element. Use the each() method to specify that you want to apply a function separately to each of the ...

  • Page 904

    Working with JSON Data876Working with JSON DataXML has been considered the standard way of working with data in AJAX (in fact, the X in AJAX stands for XML). The truth is, another format is actually becoming more popular. Although XML is easy for humans (and computer programs) to read, it’s a l...

  • Page 905

    Book VII Chapter 6Working with AJAX DataWorking with JSON Data877 "Jonas": { "animal": "Dog", "breed": "Cairn Terrier", "note": "The dog that currently owns me"}}Note a couple of things: ✦ The data is a b...

  • Page 906

    Working with JSON Data878 <script type = "text/javascript"> $(init); function init(){ $.getJSON("pets.json", processResult); } // end init function processResult(data){ $("#output").text(""); for(petName in data){ ...

  • Page 907

    Book VII Chapter 6Working with AJAX DataWorking with JSON Data879 2. Put default text in the output div. Put some kind of text in the output div. If the AJAX doesn’t work, you’ll see this text. If the AJAX does work, the contents of the output div will be replaced by a definition list. 3. A...

  • Page 908

    Working with JSON Data880 function processResult(data){ $("#output").text(""); for(petName in data){ var pet = data[petName]; $("#output").append("<h2>" + petName + "<h2>"); $("#output").a...

  • Page 909

    Book VII Chapter 6Working with AJAX DataWorking with JSON Data881 8. Set the detail name as the definition term. Surround each detail name with a <dt></dt> pair. (Don’t forget to escape the slash character to avoid an HTML validation warning.) $("#output").append...

  • Page 910

    882 Book VII: Integrating the Client and Server with AJAXwww.freepdf-books.com

  • Page 911

    Chapter 7: Going MobileIn This Chapter✓ Improving mobile accessibility✓ Using media queries to build responsive designs✓ Working with the jQuery mobile library✓ Building mobile-friendly interfaces✓ Adding collapsible interface elements✓ Building multi-page applications with jQuery mob...

  • Page 912

    Thinking in Mobile884will but unreadable on a phone. Consider using a larger font size if you expect mobile users. ✦ Make the user interface larger: It’s also a great idea to make buttons larger because they will need to be pressed by thick fingers rather than a tiny mouse. If you’re using ...

  • Page 913

    Book VII Chapter 7Going MobileBuilding a Responsive Site885Although this can work, it is often difficult to make the screen readable for all screen sizes. If you create a customized layout as described in this chapter, you can set the default behavior of the screen to respond to your improved lay...

  • Page 914

    Building a Responsive Site886 Figure 7-1: When the page is wider than 500 pixels, it shows black text on a white background. When the browser is wider than 500 pixels, you can see black text on a white background. But make the screen narrower, and you see something interest-ing, as shown in Figu...

  • Page 915

    Book VII Chapter 7Going MobileBuilding a Responsive Site887 wider than 500 pixels, it shows black text on a white background. </p> <p> When the page is narrower than 500 pixels, the colors reverse, giving white text on a black background. </p></body></...

  • Page 916

    Making Your Page Responsive888Here’s how to build a page that adapts to the screen width: 1. Build your site as usual. This is one place where that whole “separate content from layout” thing really pays off. The same HTML will have two different styles. 2. Apply a CSS style in the normal w...

  • Page 917

    Book VII Chapter 7Going MobileMaking Your Page Responsive889screen sizes, but true responsive design goes a step farther by recognizing that the entire layout may need to be changed (not just shrunk) in certain circumstances.As an example, take a look at the page in Figure 7-3.When viewed on a n...

  • Page 918

    Making Your Page Responsive890 <meta charset="UTF-8"> <link rel = "stylesheet" type = "text/css" href = "responsiveWide.css" /> <link rel = "stylesheet" type = "text/css" href = "respons...

  • Page 919

    Book VII Chapter 7Going MobileMaking Your Page Responsive891 <div id="content"> <p> Try this page on different sizes of screens. </p> <p> On wider browsers, it will have a two-column layout. On a smaller screen (like ...

  • Page 920

    Making Your Page Responsive892} nav { background-color: green; float: left; width: 150px; color: white; height: 400px;} #content { background-color: yellow; float: left; width: 440px; height: 400px; padding-left: 10px;} footer { color: white; background-color: gray; clear: both; tex...

  • Page 921

    Book VII Chapter 7Going MobileMaking Your Page Responsive893page to be in a single column taking up most of the screen width. I also want to slightly increase the overall text size. Only change the CSS nec-essary to make your page adapt to the narrower screen.Here’s the code for the responsiveN...

  • Page 922

    Using jQuery Mobile to Build Mobile Interfaces894 4. Set the heights to automatic. In the wide presentation, it made sense to give each column a specific height. That doesn’t make sense in the more fluid mobile presentation. Set the height to automatic to override the heights indicated in the ...

  • Page 923

    Book VII Chapter 7Going MobileUsing jQuery Mobile to Build Mobile Interfaces895 </p> <ul data-role = "listview"> <li>This is an ordinary list</li> <li>Coded to look like</li> <li>a mobile list</li> &...

  • Page 924

    Using jQuery Mobile to Build Mobile Interfaces896 2. Include the standard jQuery library. Much of the code is based on jQuery, so integrate the jQuery library as well. Once again, I pull jQuery from the main jQuery website. 3. Incorporate the jQuery mobile library. This is a JavaScript library ...

  • Page 925

    Book VII Chapter 7Going MobileUsing jQuery Mobile to Build Mobile Interfaces897 10. Convert lists to mobile listviews. Lists also have special conventions in the mobile world. You can use the (sing along with me now . . .) data-role attribute to turn any list into a listView. 11. Build a footer....

  • Page 926

    Using jQuery Mobile to Build Mobile Interfaces898As the user clicks on a book, the hidden content is revealed, as you can see in Figure 7-7.Figure 7-7: The selected contents expand, and other contents are hidden.The collapsible content trick is very similar to the standard jQuery mobile example...

  • Page 927

    Book VII Chapter 7Going MobileUsing jQuery Mobile to Build Mobile Interfaces899 <div data-role = "content"> <div data-role = "collapsible-set" data-theme = "c" data-content-theme = "b"> <div data-role = "coll...

  • Page 928

    Using jQuery Mobile to Build Mobile Interfaces900 6. Add some sort of header in each collapsible. Any headline tag (<H1> through <H6>) will be used as the always-visible handle for the collapsible element. 7. Non-header content will be hidden. Any other content of the collapsible el...

  • Page 929

    Book VII Chapter 7Going MobileUsing jQuery Mobile to Build Mobile Interfaces901So far, this application looks just like the other jQuery mobile apps you’ve seen so far. One thing is different, and that’s the button in the header. It’s very common for mobile apps to have navigation buttons i...

  • Page 930

    Using jQuery Mobile to Build Mobile Interfaces902 ✦ CSS and JavaScript resources only need to be loaded once: This keeps the system consistent and improves load times slightly. ✦ There’s no lag time: When the document loads, the whole thing is in memory, even if only one part is visible at ...

  • Page 931

    Book VII Chapter 7Going MobileUsing jQuery Mobile to Build Mobile Interfaces903 <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" /> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script&...

  • Page 932

    Using jQuery Mobile to Build Mobile Interfaces904 </div> <div id="foot" data-role = "footer" data-position = "fixed"> from HTML All in One for Dummies </div> </div> <div id = "page3" data-role = "page&quo...

  • Page 933

    Book VII Chapter 7Going MobileGoing from Site to App905 4. Name each of the page-level divs with the id attribute. Because the user will be flipping through the pages, each page needs some sort of identifier. Give each page a unique id attribute. I went with the rather uninspired page1, page2, a...

  • Page 934

    Going from Site to App906know everything you need to make apps that work on mobile devices. Better yet, you don’t need to learn a new language or get permission from the app store or purchase a license, as you do for native apps.There’s a couple of wonderful tricks you can do for iOS users. Y...

  • Page 935

    Book VII Chapter 7Going MobileGoing from Site to App907Again, this is an Apple-specific solution. There isn’t an easy way to achieve the same effect on the Android devices.Storing your program offlineNow your program is looking a lot like an app, except it only runs when you’re connected to t...

  • Page 936

    Going from Site to App908type needs to be configured on the server. You might have to ask your server administrator to set this option in the .htaccess file for your account:addtype text/cache-manifest .manifest Note that it can take the cache-manifest mechanism several hours to recog-nize chang...

  • Page 937

    actionURI(http://www.dummies.com/extras/html5css3aio):Visit actionURI(http://www.dummies.com/extras/html5css3aio):www.dummies.com/extras/html5css3aio for more on what’s next for the web.Part VIIIMoving from Pages to Siteswww.freepdf-books.com

  • Page 938

    Contents at a Glance Contents at a GlanceChapter 1: Managing Your Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . .911Understanding Clients and Servers ...............................................................................911Creating Your Own Server with XAMPP ..............

  • Page 939

    Chapter 1: Managing Your ServersIn This Chapter✓ Understanding the client/server relationship✓ Reviewing tools for client-side development✓ Gathering server-side development tools✓ Installing a local server with XAMPP✓ Setting essential security settings✓ Choosing a remote server✓ ...

  • Page 940

    Understanding Clients and Servers912 ✦ Clients might have wonderful resources. Client machines may have mul-timedia capabilities, a mouse, and real-time interactivity with the user. ✦ Clients are limited. Web browsers and other client-side software are often limited so that programs accessed ...

  • Page 941

    Book VIII Chapter 1Managing Your ServersUnderstanding Clients and Servers913 ✦ Text editor: Almost all web development happens with plain-text files. A standard text editor should be part of your standard toolkit. I prefer Komodo Edit because it handles all the languages described in this book ...

  • Page 942

    Creating Your Own Server with XAMPP914 ✦ An FTP server: Sometimes, you want the ability to send files to your server remotely. The FTP server allows this capability. Again, you proba-bly don’t need this item for your own machine, but you definitely should know about it when you use a remote h...

  • Page 943

    Book VIII Chapter 1Managing Your ServersCreating Your Own Server with XAMPP915 If you use Windows, you may want to change where the package is installed because the program files directory causes problems for some users. I nor-mally install XAMPP in root of the C:\ drive on Windows installations....

  • Page 944

    Creating Your Own Server with XAMPP916Testing your XAMPP configurationEnsure that Apache and MySQL are running, and then open your web browser. Set the address actionURI(http://localhost):to http://localhost, and you see a screen like the one shown in Figure 1-2. Figure 1-2: The XAMPP main page...

  • Page 945

    Book VIII Chapter 1Managing Your ServersCreating Your Own Server with XAMPP917program is immediately being called. Although this program displays the XAMPP welcome page, you don’t usually want that to happen.Rename index.php to index.php.old or something similar. It’s still there if you want ...

  • Page 946

    Creating Your Own Server with XAMPP918 ✦ Treat your server only as a local asset. Don’t run a home installation of Apache as a production server. Use it only for testing purposes. Use a remote host for the actual deployment of your files. It’s prepared for all the security headaches. ✦ Ru...

  • Page 947

    Book VIII Chapter 1Managing Your ServersCreating Your Own Server with XAMPP919 Figure 1-5: Changing the MySQL root password. Security is always a compromise. When you add security, you often intro-duce limits in functionality. For example, if you changed the root password for MySQL, some of the ...

  • Page 948

    Choosing a Web Host920 If you’re having troubles getting Apache to start, take a look at the other pro-grams you have running. Sometimes other programs use the same ports that XAMPP needs, and cause problems. Messaging programs (like Skype) are notorious for this. If you can’t start Apache wh...

  • Page 949

    Book VIII Chapter 1Managing Your ServersChoosing a Web Host921sites. Some have bandwidth restrictions and close your site if you draw too many requests. ✦ How much space are you given? Ordinary web pages and databases don’t require a huge amount of space, but if you do a lot of work with imag...

  • Page 950

    Managing a Remote Site922Connecting to a hosting serviceThe sample pages for this book are hosted on Freehostia.com, an excellent, low-cost hosting service. You can find many great hosting services, but the rest of the examples in this chapter use Freehostia, where the examples for this book are ...

  • Page 951

    Book VIII Chapter 1Managing Your ServersManaging a Remote Site923 Figure 1-7: This file management tool allows you to manipulate the files on your system. In this particular case, all my web files are in actionURI(http://www/aharrisbooks.net):the www/aharrisbooks.netactionURI(http://www/aharrisb...

  • Page 952

    Managing a Remote Site924You can create or edit files with a simple integrated editor: Build a new file with the Create File button. Type a filename into the text area and click the button. You can also click the edit button next to a file, and the file will open in the editor. In either case, th...

  • Page 953

    Book VIII Chapter 1Managing Your ServersManaging a Remote Site925Using FTP to manage your siteMost of the work is done on a local machine and then sent to the server in a big batch. (That’s how I did everything in this book.) The standard web-based file management tools are pretty frustrating w...

  • Page 954

    Managing a Remote Site926 ✦ It’s free and open source. That’s always a bonus. ✦ It works the same on every OS. If I’m on Windows, Linux, or Mac, it works the same. ✦ It’s easy to use. It feels a lot like a file manager.Figure 1-11 shows FileZilla running in my browser. Figure 1-11...

  • Page 955

    Book VIII Chapter 1Managing Your ServersManaging a Remote Site927 There’s a place in the dialog box to enter your login information. Put the address (which usually begins with ftp://) in the host box, with your username and password in the other boxes. You can typically leave the port box blan...

  • Page 956

    Naming Your Site928 7. Drag files to transfer them. To transfer files between machines simply drag them. Drag from the local machine to the remote machine to upload, or in the other direction to download them. You can move many files at a time in this manner. 8. Watch for errors. Most of the ti...

  • Page 957

    Book VIII Chapter 1Managing Your ServersNaming Your Site929 ✦ IP addresses are used to find computers. Any time you request a web page, you’re looking for a computer with a particular IP address. For example, the Google IP address is 66.102.9.104. Type it into your browser address bar, press ...

  • Page 958

    Naming Your Site930 3. Pick a subdomain. In a free hosting service, the main domain actionURI(http://freehostia.com):(freehostia.com, for example) is often chosen for you. Sometimes, you can set a subdomain (like actionURI(htt://mystuff.freehostia.com):mystuff.freehostia.comactionURI(htt://mystu...

  • Page 959

    Book VIII Chapter 1Managing Your ServersManaging Data Remotely931 6. If the domain name is available to register and you want to own it, purchase it immediately. If a domain is available to transfer, it means that somebody else prob-ably owns it. Don’t search for domains until you’re ready ...

  • Page 960

    Managing Data Remotely932This database creation step happens because you don’t have root access to MySQL. (If everybody had root access, chaos would ensue.) Instead, you usually have an assigned username and database name enforced by the server. On Freehostia, all database names begin with the ...

  • Page 961

    Chapter 2: Planning Your SitesIn This Chapter✓ Planning multipage websites✓ Working with the client✓ Analyzing the audience✓ Building a site plan✓ Creating HTML and CSS templates✓ Fleshing out the projectA t some point, your web efforts begin to grow. Rather than think about single we...

  • Page 962

    Planning a Larger Site934Obviously, the skills of web design are critical to building a website, but a broader skill set is required when creating something larger than individual pages.If you’re starting to build a more complicated website, you need to have a plan, or else you won’t succeed....

  • Page 963

    Book VIII Chapter 2Planning Your SitesUnderstanding the Client935Ensuring that the client’s expectations are clearThe short answer to the question of whether a client’s expectations are clear is, “Not usually.”A client who truly understands the Internet and knows what it takes to real-ize...

  • Page 964

    Understanding the Client936 ✦ Does the client have a remuneration strategy? If you will be paid for your work, find out how you will be paid and whether it’s hourly or by the project. If you have a business arrangement, treat it as such and write out a contract. Even if the page is written fo...

  • Page 965

    Book VIII Chapter 2Planning Your SitesUnderstanding the Audience937method is the best way to see whether your assumptions are correct and the site is doing what it needs to do. For this discussion, I’m assuming you’re building the entire site manually. In Chapter 3 of this minibook, I explain...

  • Page 966

    Understanding the Audience938these different sites. If you’re going to a university site, in a student mindset, you want quick, reliable information. If, after you sign up for classes, you’re looking for a salon, you likely want to be pampered. Websites are experi-ences. The design of the sit...

  • Page 967

    Book VIII Chapter 2Planning Your SitesBuilding a Site Plan939being professors. And they let me have it! Be willing to adjust your expecta-tions after you meet real users. (For professional work, you must meet and watch real users use your site.)Building a Site PlanOften, the initial work on a maj...

  • Page 968

    Building a Site Plan940 Figure 2-2: This chart shows an organized represen­tation of the data. Course InfoDegree InfoN100SectionsOther classesSectionsSections699ACSRequirementsAdvisingBSAdvisingRequirementsMSRequirementsAdvisingPhDRequirementsAdvisingPeopleFacultyFacilitiesLabsSystem FAQKey car...

  • Page 969

    Book VIII Chapter 2Planning Your SitesBuilding a Site Plan941 ✦ Provide representative data. Not every single scrap of information is necessary here. The point is to have enough data so you can see the relationships among data. ✦ Keep in mind that this diagram does not represent the site desi...

  • Page 970

    Building a Site Plan942The site diagram is a bit different from the overview for these reasons: ✦ Each box represents a page. Now you have to make some decisions about how the pages are organized. Determine at which level of the overview you have separate pages. For example, are all the course ...

  • Page 971

    Book VIII Chapter 2Planning Your SitesCreating Page Templates943Creating Page TemplatesIf you’ve developed a site diagram, you should have a good feel for the over-all requirements of the web development project. You should know how many layouts you need and the general requirements for each on...

  • Page 972

    Creating Page Templates944 ✦ Build a page sketch following these guidelines for each page template in your site. If you have three page designs, for example, you need three separate diagrams.Standard template for CS siteAll DivFixed width 800 pxCentered in browserFont: double sizeColor: WhiteBa...

  • Page 973

    Book VIII Chapter 2Planning Your SitesCreating Page Templates945Building the HTML template frameworkWith a page layout in place, you can finally start writing some code. Begin with your standard page layout diagram and create an HTML template to implement the diagram in working code. The HTML tem...

  • Page 974

    Creating Page Templates946Here’s the HTML code for my prototype:<!DOCTYPE html><html lang = "en-US"> <head> <meta charset = "UTF-8"> <title>CS Standard Template</title> <link rel = "stylesheet" type = &quo...

  • Page 975

    Book VIII Chapter 2Planning Your SitesCreating Page Templates947Creating page stylesWith an HTML framework in place, you can start working on the CSS. The best way to incorporate CSS is by following these steps: 1. Begin with the page template diagram. It should have all the information you need...

  • Page 976

    Creating Page Templates948#all { background-color: white; border: 1px solid black; width: 800px; margin-top:2em; margin-left: auto; margin-right: auto; min-height: 600px;} #heading { background-color: #A11204; background-image: url("cbBackground.png"); color: #FFFFFF; height:...

  • Page 977

    Book VIII Chapter 2Planning Your SitesCreating Page Templates949#footer { color: #FFFFFF; background-color: #000000; border: 1px solid #A11204; float: left; clear: both; width: 100%; text-align: center;}Figure 2-6 shows the standard template with the CSS attached. Figure 2-6: The HTML te...

  • Page 978

    Fleshing Out the Project950 2. Identify data requirements in your site diagram. Find out where on the site diagram you’re getting data. Determine which data you’re retrieving and record this information on the site diagram. 3. Create a third normal form ER diagram. Don’t bother building a...

  • Page 979

    Book VIII Chapter 2Planning Your SitesFleshing Out the Project951 2. Proofread everything. Almost nothing demolishes credibility as quickly as sloppy writing. Get a quality proofreader or copy editor to look over everything on the site to check for typos and spelling errors. If your page contain...

  • Page 980

    952 Book VIII: Moving from Pages to Siteswww.freepdf-books.com

  • Page 981

    Chapter 3: Introducing Content Management SystemsIn This Chapter✓ Understanding the need for content management systems✓ Previewing typical content management systems✓ Installing a content management system✓ Adding content to a content management system✓ Setting up the navigation struct...

  • Page 982

    Overview of Content Management Systems954framework for manipulating and displaying that data. It’s a good deal for you and the client.A content management system (CMS) is designed to address exactly these issues, as this chapter will show you.Overview of Content Management SystemsCMSs are used ...

  • Page 983

    Previewing Common CMSs955Book VIII Chapter 3Introducing Content Management SystemsPreviewing Common CMSsTo get a true feel for the power of CMSs, you should test-drive a few. The won-derful resouractionURI(http://www.opensourcecms.com):ce www.opensourcecms.comactionURI(http://www.opensourcecms.co...

  • Page 984

    Previewing Common CMSs956 ✦ Specialized educational content: Moodle was put together by hundreds of passionate (and geeky) teachers, so it has all kinds of support for vari-ous teaching methodologies.Community-created software can be very good (as Moodle is) because it’s built by people who k...

  • Page 985

    Previewing Common CMSs957Book VIII Chapter 3Introducing Content Management SystemsDrupalDrupal is one of the most popular multipurpose CMSs out there. Intended for larger sites, it’s more involved than the specialty CMSs — although it can do almost anything.Figure 3-4 shows a basic site runn...

  • Page 986

    Previewing Common CMSs958 ✦ Software sites: A CMS like Drupal is an ideal place to post information about your software, including downloads, documentation, and user support. ✦ Forums: Although you can find many dedicated forum packages, Drupal supports several good forum tools. ✦ Blogging:...

  • Page 987

    Previewing Common CMSs959Book VIII Chapter 3Introducing Content Management Systems 1. Download the latest version of WebsiteBaker atactionURI(http://www.websitebaker2.org/en/home): www.websiteactionURI(http://www.websitebaker2.org/en/home): actionURI(http://www.websitebaker2.org/en/home):baker2.o...

  • Page 988

    Previewing Common CMSs960 2. Ensure folders are writable. The CMS will need to write files to the server. If you’re in a Unix-based system, you may have to check the file permissions to ensure all files and folders specified in this section can be written to. Each specified file or folder can ...

  • Page 989

    Previewing Common CMSs961Book VIII Chapter 3Introducing Content Management Systems Instead of installing the CMS manually, many hosting services have automated installation scripts for popular CMSs that you can use. Freehostia has built-in support for WebsiteBaker, but I find the automated system...

  • Page 990

    Previewing Common CMSs962Getting an overview of WebsiteBakerThe administration page (refer to Figure 3-7) is the control panel you and other administrators use to build the site. The administration page’s tools are the foundation of the entire site: ✦ Pages: Where you add the primary content...

  • Page 991

    Previewing Common CMSs963Book VIII Chapter 3Introducing Content Management Systems 5. Click the Add button to add the page. A screen similar to Figure 3-9 appears. Figure 3-9: Now you’re at a nice page editor. Using the WYSIWYG editorThe purpose of the CMS is to make editing a website withou...

  • Page 992

    Previewing Common CMSs964editor has a number of useful tools that make creating and editing much like working with a word processor. ✦ Predefined fonts and styles: The user can choose fonts and styles from drop-down menus, unaware that these options are taking advantage of predefined CSS styles...

  • Page 993

    Previewing Common CMSs965Book VIII Chapter 3Introducing Content Management SystemsThe WYSIWYG page is the most commonly used page type (especially by nontechnical users) but it’s not the only option. The standard edition of WebsiteBaker also comes with a number of other default page types: ✦ ...

  • Page 994

    Previewing Common CMSs966 ✦ Form: Allows you to build a basic HTML form without knowing any HTML. The administrator can add all the normal form elements. Figure 3-13 shows the form editor in action. When the user enters form data, the content is automatically e-mailed to the administrator and ...

  • Page 995

    Previewing Common CMSs967Book VIII Chapter 3Introducing Content Management Systems You are not limited to these page types. See the section “Adding new func-tionality” later in this chapter for information on how to add additional page types to your system.Figure 3-14: The news page type all...

  • Page 996

    Previewing Common CMSs968Changing the templateOne of the primary goals of a CMS is to separate the visual layout from the contents. So far, you’ve seen how to modify the contents, but you’ll also want to change the appearance of the page. The visual settings of a site are all based on a templ...

  • Page 997

    Previewing Common CMSs969Book VIII Chapter 3Introducing Content Management SystemsAdding additional templatesThe standard installation of WebsiteBaker includes only a few templates. Typically, you’ll want to work with additional templates. Fortunately, there are hundreds of great templates avai...

  • Page 998

    Previewing Common CMSs970 Figure 3-17: You can install any template onto your existing system. The Multiflex-3 template is one of the most commonly used templates on the Internet. The original design actionURI(http://www.oswd.org/design/preview/id/3626):(www.oswd.org/design/preview/id/3626) was...

  • Page 999

    Building Custom Themes971Book VIII Chapter 3Introducing Content Management Systems 1. Find a module you wish to test. Go to the AMASP site and browse the various modules until you find one you like; there’s about a dozen. For this example, I’m looking at the (unimaginatively named) Image Gal...

  • Page 1000

    Building Custom Themes972 1. Find a starting template you like. Often I have clients look over the Templates repository actionURI(http://www.websitebaker2.org/template/pages/templates.php):(www.websiteactionURI(http://www.websitebaker2.org/template/pages/templates.php): actionURI(http://www.webs...

  • Page 1001

    Building Custom Themes973Book VIII Chapter 3Introducing Content Management SystemsOne of the reasons I like WebsiteBaker so much is how relatively simple the template structure is compared to other CMSs. The directory contains a rela-tively small number of files: ✦ index.php: This PHP file is t...

  • Page 1002

    Building Custom Themes974 the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Website Baker is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTI...

  • Page 1003

    Building Custom Themes975Book VIII Chapter 3Introducing Content Management Systems ✦ show_menu(menuID): This is a powerhouse of a function. It analyzes your site structure and uses it to build a navigation structure. It takes a parameter, which is the level of menu. (Typically the left menu is ...

  • Page 1004

    Building Custom Themes976 5. Test on a local server. You can make changes directly on the files in your local server. Just reload the page after every change to make sure the changes are being reflected. Of course, you need to have the template installed in your system.Packaging your templateA t...

  • Page 1005

    Chapter 4: Editing GraphicsIn This Chapter✓ Introducing Gimp✓ Managing the main tools✓ Selecting image elements✓ Working with layers✓ Understanding filters✓ Creating a tiling background✓ Building banner imagesH TML and CSS are powerful tools, but sometimes you still need to use a gr...

  • Page 1006

    Choosing an Editor978Choosing an EditorFortunately, great programs that make all these tasks quite easy to perform are available. Raster-based graphics editors are designed to solve exactly this type of problem and many more. A number of important graphics tools are used in web development: ✦ A...

  • Page 1007

    Book VIII Chapter 4Editing GraphicsIntroducing Gimp979you are interested in playing with vector graphics, I recommend looking into the excellent free program Inkscape. It has native support for SVG, which is the most universal vector standard for web browsers.Introducing GimpIf you haven’t alre...

  • Page 1008

    Introducing Gimp980 I have the Change Foreground Color dialog open in Figure 4-1, and I simply double-clicked the foreground color in the main toolbox to open this dialog. Gimp tends to open a lot of dialogs, which might bother some people. Also, I want to illustrate how powerful the color choos...

  • Page 1009

    Book VIII Chapter 4Editing GraphicsIntroducing Gimp981 ✦ Paintbrush: The Paintbrush tool is similar to the Pencil tool, but it uses a technique called anti-aliasing to make smoother edges. Like the Pencil tool, the Brush tool can use many different pen shapes. ✦ Eraser: The Eraser tool is use...

  • Page 1010

    Introducing Gimp982 ✦ Clone: The powerful Clone tool allows you to grab content from one part of an image and copy it to another part of the image. This tool is often used in photo retouching to remove scars and blemishes. ✦ Fill: The Fill tool is used to fill an area with a color or pattern....

  • Page 1011

    Book VIII Chapter 4Editing GraphicsIntroducing Gimp983 Figure 4-4: These tools are used for selecting parts of an image. RectangleBezierEllipseFreeForegroundScissorsSelect by colorMagic ✦ Rectangle Select: The Rectangle Select tool is used to (wait for it . . .) select rectangles. Rectangle...

  • Page 1012

    Introducing Gimp984 ✦ Foreground Select: The Foreground Select tool is a multipass tool that simplifies pulling part of an image from the rest. On the first pass, use the Lasso tool to choose the general part of the image you want to select. The image will show a selection mask with selected pa...

  • Page 1013

    Book VIII Chapter 4Editing GraphicsIntroducing Gimp985You can see the Tool Options dialog box for any tool by double-clicking the tool in the Toolbox. Generally, I dock the Tool Options dialog box to the main Toolbox tabs because it’s so frequently used.UtilitiesGimp also comes with a number of...

  • Page 1014

    Understanding Layers986 ✦ Align: The Align tool simplifies lining up various elements with each other. ✦ Crop: Used to crop unwanted border areas from an image. ✦ Text: Adds editable text to the image. The Text tool works with layers, so check the upcoming “Understanding Layers” section...

  • Page 1015

    Book VIII Chapter 4Editing GraphicsUnderstanding Layers987Figure 4-7: The Layers panel allows you to manipulate layers.The primary area of the Layers panel is the window, showing a stack of layers. The background is on the bottom of the stack, and any other layers are on top. Anything on an uppe...

  • Page 1016

    Introducing Filters988Each layer has two icons next to it that you can activate. The eye icon toggles the layer’s visibility. The link icon allows you to link two or more layers together. Each layer also has a name. You can double-click the layer name to change it. This is especially useful whe...

  • Page 1017

    Book VIII Chapter 4Editing GraphicsSolving Common Web Graphics Problems989 ✦ Brightness/Contrast: Lets you adjust the brightness (overall value) and contrast of a particular layer. ✦ Color balance: Allows you to adjust the relative amounts of red, green, and blue in a layer, which can be used...

  • Page 1018

    Solving Common Web Graphics Problems990 Building a banner graphicNearly every commercial website has a banner graphic — a special graphic, usually with a set size (900×100 is common), that appears on every page. Normally, if you’re modifying a CSS template, you have a default banner graphic...

  • Page 1019

    Book VIII Chapter 4Editing GraphicsSolving Common Web Graphics Problems991 5. Duplicate the text layer. In the Layers panel, make a copy of the text layer. Select the lower of the two text layers (which will become a shadow). 6. Blur the shadow. With the shadow layer selected, apply the Gaussia...

  • Page 1020

    Solving Common Web Graphics Problems992 Figure 4-9: The steps for building a banner. Normally, when you save to another format, a dialog box of options appears. If in doubt, go with the default values.Figure 4-10 shows the final banner image. I included the XCF and PNG files on the website. Fe...

  • Page 1021

    Book VIII Chapter 4Editing GraphicsSolving Common Web Graphics Problems993 infinitely in both the X and Y axes. You can also set the background to repeat horizontally (repeat-x), vertically (repeat-y), or not at all (no-repeat).The goal of a tiled background is to make a relatively small graphic ...

  • Page 1022

    Solving Common Web Graphics Problems994on the left of the gradient, and lighter colors map to the left. You can adjust colors, so don’t worry if the colors aren’t exactly what you want. (If you want, you can make your own gradient with the gradient editor by clicking the Gradient dialog box...

  • Page 1023

    Chapter 5: Taking Control of ContentIn This Chapter✓ Approximating CMS with Server Side Includes (SSI)✓ Reviewing client-side includes using AJAX✓ Using PHP includes to build a basic CMS-style system✓ Building a data-based CMS✓ Creating a form for modifying contentC ommercial sites tod...

  • Page 1024

    Building a “Poor Man’s CMS” with Your Own Code996 Figure 5-1: This web page appears to be a standard page. Even if you view the source code in the browser, you don’t find anything unusual about the page.However, if you look at the code in a text editor, you find some interesting discover...

  • Page 1025

    Book VIII Chapter 5Taking Control of ContentBuilding a “Poor Man’s CMS” with Your Own Code997 <div id = "footer"> <!--#include virtual = "footer.html" --> </div> <!-- end footer div --> </div> <!-- end all div --> ...

  • Page 1026

    Building a “Poor Man’s CMS” with Your Own Code998 Like PHP code, SSI code doesn’t work if you simply open the file in the browser or drag the file to the window. SSI requires active participation from the server; to run an SSI page on your machine, therefore, you need to use localhost, as...

  • Page 1027

    Book VIII Chapter 5Taking Control of ContentBuilding a “Poor Man’s CMS” with Your Own Code999 href = "csStd.css" /> <script type = "text/javascript" src = "jquery-1.10.2.min.js"></script> <script type = "text/jav...

  • Page 1028

    Building a “Poor Man’s CMS” with Your Own Code1000The same document structure can be used with very different content by changing the JavaScript. If you can’t create a full-blown CMS (because the server doesn’t allow SSI, for example) but you can do AJAX, this is an easy way to separate...

  • Page 1029

    Book VIII Chapter 5Taking Control of ContentCreating Your Own Data-Based CMS1001 3. Include the HTML file. Each PHP snippet does nothing more than include the appropriate HTML.Creating Your Own Data-Based CMSIf you’ve come this far in the chapter, you ought to go all the way and see how a rela...

  • Page 1030

    Creating Your Own Data-Based CMS1002 cmsBlock, blockType, cmsPage WHERE cmsBlock.blockTypeID = blockType.blockTypeID; INSERT INTO cmsPage VALUES ( null, 'main page'); INSERT into blockType VALUES (null, 'head');INSERT into blockType VALUES (null, 'menu');INSERT into blockType VALUES ...

  • Page 1031

    Book VIII Chapter 5Taking Control of ContentCreating Your Own Data-Based CMS1003 <li>Selectors, Class, and Style</li> <li>Borders and Backgrounds</li> <li>Levels of CSS</li></ol> ', 1); INSERT INTO cmsBlock VALUES ( null, 5, null, 'see <a ...

  • Page 1032

    Creating Your Own Data-Based CMS1004 Most of the data is being read as HTML, but it’s still text data. I included the entire SQL file, including the INSERT statements, on the companion website as buildCMS.sql.Writing a PHP page to read from the tableThe advantage of using a data-based approach ...

  • Page 1033

    Book VIII Chapter 5Taking Control of ContentCreating Your Own Data-Based CMS1005 } // end foreach} catch(PDOException $e) { echo 'ERROR: ' . $e->getMessage();} // end try?> <body> <div id = "all"> <!-- This div centers a fixed-width layout --> ...

  • Page 1034

    Creating Your Own Data-Based CMS1006if ($pageID == ""){ $pageID = 1;} // end if Note that I’m using a sneaky trick to indicate the page. The menu links will all call the same program, but with a different pageID: <ul> <li><a href = "dbCMS.php?page...

  • Page 1035

    Book VIII Chapter 5Taking Control of ContentCreating Your Own Data-Based CMS1007 $head = $row["title"]; } else if ($row["block"] == "menu"){ $menu = $row["content"]; } else if ($row["block"] == "content1"){ $c1Title ...

  • Page 1036

    Creating Your Own Data-Based CMS1008way to add data to the CMS. Figure 5-4 shows the buildBlock.html page. This page allows authorized users to add new blocks to the system and produces the output shown in Figure 5-5. Figure 5-4: A user can add content, which updates the database. After a fe...

  • Page 1037

    Book VIII Chapter 5Taking Control of ContentCreating Your Own Data-Based CMS1009 Figure 5-6: This page is simply another set of page blocks added by the user. The system is simple but effective. The user builds blocks, and these blocks are constructed into pages. First, look over the buildBlock....

  • Page 1038

    Creating Your Own Data-Based CMS1010 <div id = "all"> <div id = "heading"> <h1>Build a new block</h1> </div> <div class = "content"> <form action = "buildBlock.php" method = "...

  • Page 1039

    Book VIII Chapter 5Taking Control of ContentCreating Your Own Data-Based CMS1011 ✦ Ask for a password: You don’t want just anybody modifying your forms. Include a password to make sure only those who are authorized add data. ✦ Get other data needed to build a block: Think about the INSERT q...

  • Page 1040

    Creating Your Own Data-Based CMS1012 //connect to database $con= new PDO('mysql:host=host;dbname=dbName', "user", "pwd"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //create an INSERT statement based on input $stmt = $con->prepare('INS...

  • Page 1041

    Book VIII Chapter 5Taking Control of ContentCreating Your Own Data-Based CMS1013 6. Build and execute the query. Send the query to the database with the prepare/execute mechanism. Note that an INSERT command doesn’t return a data result, so there’s no need to do a fetch command. However, the...

  • Page 1042

    1014 Book VIII: Moving from Pages to Siteswww.freepdf-books.com

  • Page 1043

    IndexSpecial Characters and Numerics-- operator, 412<!– –> (comment) tag, 13!= (not equal) conditional operator, 403, 574!== comparison operator, 634, 636# identifier, 785$( ) function, 780–782, 785$ operator, 474$ variable character, 540% wildcard value, 692& (ampersands), 558&...

  • Page 1044

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1016' ' (single quotes), 384, 539, 680, 713111 permission, 925200 = OK response code, 770400 = Bad Request response code, 770404 = Not Found response code, 770408 = Request Timeout response code, 770500 = Internal Server Error response code, 7706...

  • Page 1045

    Index1017opening connections to server, 768–769sending request and parameters, 769Google Chrome, 47improving with jQueryadding or removing styles, 788–790AJAX requests with, 791–794changing styles, 783–785creating objects, 780–781events, 786–788, 790features of, 776–777importing fro...

  • Page 1046

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1018moving elements, 519–520sprites, 515with jQueryeasing, 808fading effect, 802general discussion, 795–797hiding and showing effects, 800–801HTML and CSS foundation for, 799initializing page, 800modifying elements, 807–817positioning, 802...

  • Page 1047

    Index1019B\b operator, 474<b> (boldface) tag, 155, 179–180back( ) function, 408, 411background imagesadding to web pages, 212–214color adjustment, 216contrast, 214, 217–218gradientscreating complex, 220–221creating simple, 220–221general discussion, 219–220radial, 222–223probl...

  • Page 1048

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1020braces ({ })conditions, 402function definition, 382, 608–609JSON notation, 455for loops, 583main objects, 877style rules, 134switch statements, 405, 580break (<br />) tag, 410, 435break statement, 406, 580breakpoints, 418, 420bugs (log...

  • Page 1049

    Index1021general discussion, 511–512strategies for, 514–515CAPTCHA mechanism, 621caret (^) operator, 473, 476carriage returns, 14Cartesian joins, 729–730Cascading Style Sheets. See CSS3case conversion, 170case statement, 405catch clause, 651<center> (centering) tag, 155, 205centered f...

  • Page 1050

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1022importing from Google, 777–778initialization functions, 781–783installing, 777manipulating classes, 788–790methods, 781modifying styles, 785–786node object, 780selecting objects, 785setting up page, 779–780jQuery UI toolkitadding ico...

  • Page 1051

    Index1023buttons, 379–384check boxes, 465–467drop-down lists, 459–461hidden fields, 391–397password fields, 391–397radio buttons, 468–470select lists (multiple select lists), 462–465text boxes/fields, 384–391, 459functionsanonymous, 451assigning prebuilt to methods, 451breaking co...

  • Page 1052

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1024modifying index.php file, 974–975packaging templates, 976prebuilt templates, 971–973characteristics of, 953–954commonly-usedDrupal, 957–958Moodle, 955–956WordPress, 956–957data-basedadding new blocks, 1011–1013allowing user-gener...

  • Page 1053

    Index1025HSB, 143HSLalpha transparency, 216fills and strokes, 487overview, 143–144specifying colors with, 145–146HSV, 143Mono, 148RGB, 143, 216selecting, 147–148Tetrad, 148Triad, 148Color Selector, Gimp, 985–986color stops, 222, 249, 487–488colorChooser program, 137cols attribute, 113co...

  • Page 1054

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1026commonly-usedDrupal, 957–958Moodle, 955–956WordPress, 956–957data-basedadding new blocks, 1011–1013allowing user-generated content, 1007–1011improving design, 1013using databases, 1001–1004writing PHP pages to read from tables, 100...

  • Page 1055

    Index1027overriding styles, 235–236precedence of style definitions, 236–237case sensitivity, 134centered fixed-width layoutsfeatures of, 307general discussion, 305limitations of, 308surrogate body, 306–307choosing, 351–352coloradding to web pages, 141–142of background images, 216backgro...

  • Page 1056

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1028transformations, 252–257transition animation, 257–259style sheetsdefined, 131setting up, 133–134textalignment, 169–170blinking, 169bold, 166–167case conversion, 170creating in graphic editors, 267creating list of fonts, 153–154embe...

  • Page 1057

    Index1029determining fields in records, 656editing recordsdeleting, 697updating, 696–697exporting data and structurecreating XML data, 702–703exporting SQL code, 700–702output formats, 698–700reasons for, 697–698joinscalculating date values, 720–726Cartesian, 729–730creating views, ...

  • Page 1058

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1030improving design, 1013using databases, 1001–1004writing PHP pages to read from tables, 1004–1007dblClick event, 790<dd></dd> (definition data) tags, 59, 879, 881DDL (Data Definition Language), 656debuggingautomatically, 427wit...

  • Page 1059

    Index1031.doc extension, 624doctype, 26<!DOCTYPE HTML> tag, 12Document Object Model (DOM)changing page color with, 375–379defined, 375style element names, 379document variable, 377$(document).ready( ) function, 782–783Dodge/Burn tool, Gimp, 984–985DOJO library, 775DOM (Document Object...

  • Page 1060

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1032menu system with vertical button listadvantages of, 321–322creating, 322–324Eeach( ) method, 875ease-in-out attribute, 262easing, 808echo statements, 539editor.css file, 973element-level styles, 225Ellipse Select tool, Gimp, 983else clause...

  • Page 1061

    Index1033fgets( ) function, 617, 626fieldsdefined, 656determining in records, 657<fieldset></fieldset> tags, 109fieldsetsdefined, 107–108, 386–387floating layouts, 282–283organizing forms with, 107–109, 278width of, 282–283figcaption semantic tag, 295figure semantic tag, 295...

  • Page 1062

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1034HTML code for, 341–342overview, 340–341general discussion, 352overview, 340fixed-width layoutscenteredfeatures of, 307general discussion, 305limitations of, 308surrogate body, 306–307general discussion, 302HTML code for, 303setting width...

  • Page 1063

    Index1035hyperlinks, 189relative measurement units, 163–164defined, 162ems, 164named sizes, 163percentage, 164specifying, 160–161strategies for, 164<font> tag, 155fontColor( ) method, 366@font-face style, 155–156font-family attribute, 150–151, 156fontsblinking, 169bold, 166–167con...

  • Page 1064

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1036organizing with, 107–109overview, 107floating layoutsbuttons, 278, 280clear attribute, 283–284colors, 279fieldset width, 282–283general discussion, 276–278labels, 278–280neatness of layout, 279–282general discussion, 105hidden fiel...

  • Page 1065

    Index1037for returning values, 434–435separation between, 432variable scope, 437–439Fuzzy Select (Magic Wand) tool, Gimp, 983, 989fwrite( ) function, 617–620, 624, 628Ggedit text editor, 38generated source, 395–397generic font names, 151–153get( ) function, 861, 874, 876get method, 556...

  • Page 1066

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1038Developer Tools window, 376, 418–419features of, 47–48general discussion, 10image borders, 208viewing generated source code, 396–397Google Fonts, 157Google queries, 558–559gradient mapping, 993–994gradientscreating complex, 220–221...

  • Page 1067

    Index1039:header filter, 817, 832<header> semantic tag, 292–294, 351headers, table, 61–62heading level one (<h1></h1>) tags, 13–14Heal tool, Gimp, 984–985height attribute, 81, 330, 334Hello World programs, 357heredocsadvantages of, 545example of, 544–545packaging outpu...

  • Page 1068

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1040buttons, 106, 119–122check boxes, 106, 116–117drop-down lists, 114–116fieldsets and legends, 107–109general discussion, 105labels, 107–109new input types, 122–127password fields, 106, 111–112radio buttons, 106, 117–119select li...

  • Page 1069

    Index1041externally linked, 103formats, 101HTML5 Doctor CSS reset, 242htmlentities( ) function, 633HTTP (hypertext transfer protocol), 70HTTP (hypertext transfer protocol) response codes, 770huedefined, 144selecting with Color Scheme Designer tool, 147–148specifying, 145hyperlinksabsolute refer...

  • Page 1070

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1042using images as text, 159–160utilities, 985–986GimpShop, 85IrfanView3D button effect, 97batch processing, 98–99blurring, 94–95brightness, 92color balance, 93contrast, 93, 217effects and filters, 93–98embossing, 95–96features of, 84...

  • Page 1071

    Index1043advantages of, 160problems with, 160process for, 158–160vector, 89wrapping text around, 269–271images directory, 973<img /> (image) tagalt attribute, 81–82drawing images, 505embedded images, 80–82height attribute, 81src attribute, 81width attribute, 81in_array( ) function, ...

  • Page 1072

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1044CSS incompatibility, 237debugging in, 420First Browser Wars, 44general discussion, 10HTML5 support in IE9, 46HTML5 support in IE10, 46image borders, 208margins and padding, 298, 339versions of, 242Internet Protocol (IP) addresses, 928–929in...

  • Page 1073

    Index1045with Chrome console, 420–422with Chrome debugger, 418–420logic errors, 424–426syntax errors, 422–424decision-making codeif statements, 399–405, 416–417for loops, 406–413switch statements, 405–406while loops, 413–417defined, 355–356embedding code, 358as first programmi...

  • Page 1074

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1046general discussion, 359–360numeric values, 369program for adding numbers, 369–370program for adding numbers provided by user, 370requesting user input, 361responding to user input, 361–362javascript: identifier, 398JavaScript Object Nota...

  • Page 1075

    Index1047widgetsaccordion tool, 821, 841–845classes used on, 831–832datepicker controls, 821, 851–852defined, 841dialog boxes, 821, 856–858icons, 822progress bars, 821selectable elements, 854–855sliders (scroll bars), 821, 851–852sortable lists, 855–856tabs tool, 821, 842, 845–850...

  • Page 1076

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1048fixed menu systems, 340–344general discussion, 352overview, 340fixed-width layoutsgeneral discussion, 302HTML code for, 303setting width, 303–305flexible box layoutsabsolute positioning versus, 345, 351browser compatibility, 348–350creat...

  • Page 1077

    Index1049general discussion, 54–55indenting, 56–57menu systems, 315–316, 321orderedcode for, 54creating, 54defined, 51general discussion, 53unorderedcharacteristics of, 51–52code for, 53creating, 52–53defined, 51for multiple select list results, 464using images as bullets, 77, 223–224...

  • Page 1078

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1050margin-right attribute, 206marginsabsolute positioning, 330box modelchanging settings, 204–205defined, 203–205positioning elements with, 205–206Internet Explorer and, 298, 339match( ) method, 471, 473, 475Math.ceil( ) function, 372–373...

  • Page 1079

    Index1051image borders, 208origin of, 45viewing generated source code, 397MP3 format, 100–101MS Access, 661MS SQL Server, 660-ms-border- image attribute, 208multidimensional arraysgeneral discussion, 444–446, 597–600main( ) function, 448–449setting up, 446–447Multiflex-3 template, 970mu...

  • Page 1080

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1052from specific fields, 689–690subsets of records, 690–691server name, 932specifying length of records, 658–659structure of data, 655–657syntax rules, 680table structure, 659–660three-tiered architecture, 662–663using phpMyAdmin to i...

  • Page 1081

    Index1053offset-y parameter, 252Ogg format, 100–101<ol></ol> (ordered list) tags, 54, 593onclick parameter, 379–380, 384, 387one-to-many relationships, 717, 731–732one-to-one relationships, 717onkeydown attribute, 522onload property, 506OOP (object-oriented programming)access mo...

  • Page 1082

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1054line width and style options, 498–499quadratic curves, 502–503pattern attribute, 481pattern memory, 478(pattern segment) operator, 474patterns, 489–491.pdf extension, 624PDF files, exporting data and structure as, 700PDO (PHP Data Object...

  • Page 1083

    Index1055creating objects, 640–641defining classes, 640–641inheritance, 647–650overview, 639–640using classes, 642–644programming flow, 536quotes, 539relationship between HTML and, 549–551sending data to PHP programscreating forms, 552–555, 563–565extracting form data, 560–562ge...

  • Page 1084

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1056progress semantic tag, 295prompt( ) command, 361prompt( ) method, 434proofs of program correctness, 427propertiesdefined, 364, 449defining, 641purpose of, 366protected keyword, 644–645protocolsdefined, 70as part of absolute references, 73as ...

  • Page 1085

    Index1057using characters in, 475–476using special characters in, 476–477rel attribute, 232relational database management systems (RDBMS), 660–661relative font measurement unitsdefined, 162ems, 164named sizes, 163percentage, 164relative motion, 808relative positioning, 340, 352relative refe...

  • Page 1086

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1058Select by Color tool, Gimp, 983SELECT command, 681, 683, 688–695, 727select event, 790select lists (multiple select lists)creating, 114–116defined, 106HTML code for, 462–463JavaScript code for, 463–465select object, 460–464<select...

  • Page 1087

    Index1059delimited dataoverview, 626–627reading CSV data, 630–633storing data in CSV files, 627–628viewing CSV data directly, 629–630e-mail, 624embedding PHP inside HTML, 550exception handling, 650–652file and directory functionschdir( ) function, 634–635generating lists of file links...

  • Page 1088

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1060setter methods, 645shading, border, 200shadow effectfor borders, 210–212for text, 212, 251–252shadowBlur method, 494shadowColor method, 494shadowOffsetX method, 494shadowOffsetY method, 494shadows, 494–495Shakespearean insult generator, ...

  • Page 1089

    Index1061<strong></strong> (strong emphasis) tagsgeneral discussion, 81, 177–179modifying display of, 179–180Structured Query Language. See MySQLStructured Query Language (SQL). See also MySQLdata types, 657–658date and time functions, 720–721injection attacks, 753overview, 65...

  • Page 1090

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1062searching with partial information, 692searching with regular expressions, 694–695sorting responses, 695–696from specific fields, 689–690subsets of records, 690–691single-table data problemsdeletion, 709fields with changeable data, 709...

  • Page 1091

    Index1063using images asadvantages of, 160problems with, 160process for, 158–160word spacing, 170wrapping, 269–271text areascreating, 112–113creating forms with, 392–393defined, 106, 391functions, 393–394generated source, 395–397text boxes/fieldschanging text in, 387–388creating, 10...

  • Page 1092

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1064three-tiered architecture, 662–663Tidy validatorfix suggestions, 31problems with, 31–32website for, 30tildes (~), 71tiled background images (seamless textures), 215–216, 977, 992–994TIME data type, 658time input type, 123time semantic ...

  • Page 1093

    Index1065url( ) keyword, 213–214url input type, 127, 884URLs (Uniform Resource Locators), 70–71usernames, as part of URL, 71Vvalidationcolor names, 135defined, 21example ofend tag error, 32overlapping tag error, 29–30overview of errors, 26sample page with errors, 23–24strategies for worki...

  • Page 1094

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1066naming, 609numeric values, 369overview, 540program for adding numbers, 369–370program for adding numbers provided by user, 370requesting user input, 361responding to user input, 361–362vector images, 89vector-based image editors, 978vertic...

  • Page 1095

    Index1067history of, 44–46HTML5 standards, 45–46image borders, 208Internet Explorerblack border shading, 200conditional comments, 238–240CSS incompatibility, 237debugging in, 420First Browser Wars, 44general discussion, 10HTML5 support in IE9, 46HTML5 support in IE10, 46image borders, 208ma...

  • Page 1096

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1068in three-tiered architecture, 662ways of working with, 533web services, 870web-based fonts, 154–155WebKit rendering engine, 45, 47–48-webkit-border-image attribute, 208web-safe color palette, 139–141website planningaudienceidentifying, 9...

  • Page 1097

    Index1069updates for book, 6W3C validator, 22, 25WebsiteBaker AMASP, 970WebsiteBaker documentation, 975WebsiteBaker downloads, 959WebsiteBaker templates, 969, 972XAMPP server package, 533WEEK( ) function, 720week input type, 124–125WEEKDAY( ) function, 720WHERE clause, 691, 696–697, 736while ...

  • Page 1098

    HTML5 and CSS3 All-In-One For Dummies, 3rd Edition1070XML (eXtensible Markup Language)AJAX and, 763–764exporting data and structure, 702–703general discussion, 20, 870–871HTML framework for, 873JSON versus, 457manipulating, 872–873processing results, 874–875retrieving, 874XMLHttpRequest...

  • Page 1099

    About the AuthorAndy Harris began his teaching life as a special education teacher. As he was teaching young adults with severe disabilities, he taught himself enough com-puter programming to support his teaching habit with freelance program-ming. Those were the exciting days when computers start...

  • Page 1100

    Thank you to Connie Santisteban. I’ve really enjoyed working with you on this project.Thank you to the copy and development editor, Linda Morris. I appreciate your efforts to make my geeky mush turn into something readable. Thanks for improving my writing.A special thanks to Claudia Snell for t...

  • Page 1101

    Publisher’s AcknowledgmentsAcquisitions Editor: Constance SantistebanProject Editor: Linda MorrisCopy Editor: Linda MorrisTechnical Editor: Claudia SnellEditorial Assistant: Annie SullivanSr. Editorial Assistant: Cherie CaseProject Coordinator: Sheree MontgomeryCover Image: actionURI(http://iSt...

  • Page 1102

    www.freepdf-books.com

  • Page 1103

    www.freepdf-books.com

  • Page 1104

    www.freepdf-books.com

  • Page 1105

    www.freepdf-books.com

  • Page 1106

    www.freepdf-books.com

  • Page 1107

    MobileAppsThere’s a Dummies App for This and ThatWith more than 200 million books in print and over 1,600 unique titles, Dummies is a global leader in how-to information. Now you can get the same great Dummies information in an App. With topics such as Wine, Spanish, Digital Photography, Cer...

Free HTML Books, HTML Book Pdf, HTML Pdf Books, HTML Pdf Books Download, HTML Pdf Books Free Download, Free HTML5 Books, HTML5 Book Pdf, HTML5 Pdf Books, HTML5 Pdf Books Download, HTML5 Pdf Books Free Download, Free ReadOnline Books, ReadOnline Book Pdf, ReadOnline Pdf Books, ReadOnline Pdf Books Download, ReadOnline Pdf Books Free Download,