Getting Hyper with Links in HTML - Adding Links, Images, and Other Media - Beginning HTML5 & CSS3 For Dummies® (2013)

Beginning HTML5 & CSS3 For Dummies® (2013)

Part III

Adding Links, Images, and Other Media

9781118657201-pp0301

pt_webextra_4CTo explore some great resources on HTML links, web images, and media, visit www.dummies.com/extras/beginninghtml5css3. You can also find examples from the book by chapter at www.dummieshtml.com/html5cafe/Chxx, where xx is a two-digit chapter number, such as 08.

In this part . . .

check Following links is what interconnects the web

check Building and using better hyperlinks

check Using images to add visual interest to web pages

check Making the most of graphics and images online

check Driving HTML5 to new heights of media madness

check Crafting user-friendly web page controls and dashboards

8

Getting Hyper with Links in HTML

In This Chapter

arrow Creating simple links

arrow Opening linked pages in new windows

arrow Setting up links to locations within a web page

arrow Creating links to things other than web pages

Hyperlinks, or simply links, connect HTML pages and other resources on the web. When you include a link on your page, you enable visitors to travel from your page to another website, another page on your site, or even another location on the same page. Without links, a page stands alone, disconnected from the rest of the web. With links, that page becomes part of the almost boundless collection of information that is the World Wide Web.

Basic Links 101

To create a link, you need

check A web address (called a Uniform Resource Locator; URL) for the website or file that's your link target. This usually starts with http://.

check Some text in your web page to label or describe the link. Make sure that the text you use says something useful about the resource being linked.

check An anchor element (<a>) with an href attribute to bring it all together. The element to create links is called an anchor element because you use it to anchor a URL to some text on your page. When users view your page in a browser, they can click the text to activate the link and visit the page whose URL you specified in that link. You insert the full URL in the href attribute to tell the link where to go.

tip_4c.epsYou can think of the structure of a basic link as a cheeseburger (or your preferred vegan substitute). The URL is the patty, the link text is the cheese, and the anchor tags are the buns. Tasty, yes?


Anchor elements aren’t block elements

Anchor elements are inline elements — that is, they apply to a few words or characters within a block of text (the text that you want to use as a link) instead of defining formatting for entire blocks of text. The anchor element typically sits inside a paragraph (<p>) or some other block element, such as a division (<div>), section (<section>), heading (<h1> through <h6>), or list item (<li>). When you create a link, you should always create it within a block element. Turn to Chapter 5 for more information on block elements.

Although many web browsers display anchors correctly even if you don’t nestle them inside block elements, some browsers (such as the following) don’t handle this breach of HTML syntax well:

check Text-only browsers for hand-held devices or mobile phones

check Text-to-speech readers for the visually impaired

Text-based browsers rely on block elements to divide up the sections of your page properly. Without a block element, these browsers might display your links in the wrong places!


For example, if you have a web page that describes HTML standards, you may want to refer web surfers to the World Wide Web Consortium (W3C) — the organization that governs all things related to HTML standards. A basic link to the W3C website, www.w3.org, looks like this:

<p>The <a href="http://www.w3.org">World Wide Web Consortium</a> is the

standards body that oversees the ongoing development of the HTML

specifications, and the WHATWG helps out with HTML5.</p>

You specify the link URL (http://www.w3.org) in the anchor element's href attribute. The text (World Wide Web Consortium) between the anchor element's opening and closing tags (<a> and </a>) describes the link.

Figure 8-1 shows how a browser displays this bit of markup.

9781118657201-fg0801

Figure 8-1: A paragraph with a link to the W3C.

tip_4c.epsYou can also anchor URLs to images so that users can click an image to activate a link. For more about creating images that link, see Chapter 9. For a detailed discussion of the ins and outs of URLs, see Chapter 1.

Exploring link options

You can link to a variety of online resources:

check Other HTML pages (either on your website or on another website)

check Different locations on the same HTML page

check Resources that aren’t even HTML pages at all, such as e-mail addresses, pictures, and text files or downloads for visitors

tip_4c.epsLink locations, captions, and destinations exert a huge influence on how site visitors perceive links. Chapter 2 covers best practices for using links in your site design. The kind of link you create is determined by what you link to and how you formulate your link markup.

Absolute links

An absolute link uses a complete URL to connect browsers to a web page or online resource.

Links that use a complete URL to point to a resource are called absolute because they provide a complete, stand-alone path to another web resource. When you link to a page on someone else’s website, the web browser needs every bit of information in the URL to find that page. The browser starts with the domain in the URL and works its way through the path to a specific file.

remember_4c.epsWhen you link to files on someone else's site, you must always use absolute URLs in the href attribute of the anchor element. Here's an example:

http://www.website.com/directory/page.html

Relative links

A relative link uses a kind of shorthand to specify a URL for a resource you’re pointing to.

Use the following guidelines with relative links in your HTML pages:

check Create relative links between resources in the same domain.

check Because both resources are in the same domain, you may omit domain information from the URL.

A relative URL uses the location of the resource you link from to identify the location of the resource you link to (for example, page.html).

A relative link is similar to telling someone that he or she needs to go to the Eastside Mall. If the person already knows where the Eastside Mall is, he or she doesn’t need additional directions. Web browsers behave the same way.

tip_4c.epsIf you use relative links on your site, your links still work if you change

check Servers.

check Domain names.

Simple links

You can take advantage of relative URLs when you create a link between pages on the same website. If you want to make a link from http://www.mysite.com/home.html to http://www.mysite.com/about.html, you can use this simplified, relative URL in an anchor element on home.html:

<p>Learn more <a href="about.html">about</a> our company.</p>

remember_4c.epsWhen a browser sees a link without a domain name, the browser assumes that the link is relative and uses the domain and path from the linking page to find the linked page. The preceding example works only if home.html and about.html are in the same directory, though.

Site links

As your site grows more complex and you organize your files into various folders, you can still use relative links. However, you must provide additional information in the relative URL to help the browser find files that don’t reside in the same directory as the file from which you’re linking.

Use ../ (two periods and a slash) before the filename to indicate that the browser should move up one level in the directory structure.

The markup for this directory navigation process looks like this:

<a href="../docs/home.html>Documentation home</a>

The notation in this anchor element instructs the browser to take these steps:

1. Move up one folder from the folder the linking document is stored in.

2. Find a folder called docs.

3. Inside that folder, find a file called home.html.

remember_4c.epsWhen you create a relative link, the location of the file to which you link is always relative to the file from which you link. As you create a relative URL, trace the path a browser takes if it starts on the page you’re linking from to get to the page to which you’re linking. That path defines the URL you need.

Avoiding common mistakes

Every web resource — site, page, or image — has a unique URL. Even one incorrect letter in a URL creates a broken link, which leads to an error page (usually the HTTP error 404 File or directory not found).

warning_4c.epsURLs are so finicky that a simple typo — sometimes even a mistake in capitalization — breaks a link. Be sure to proofread your work and heed the following tips, which help you steer clear of avoidable missteps.

If a URL doesn’t work, try these tactics:

check Check the capitalization. Some web servers (Linux and Unix, most notably) are case-sensitive (they distinguish between capital and lowercase letters). For example, such servers treat the filenames Bios.html and bios.html as different files on the web server. That means any browser looking for a particular URL must use uppercase and lowercase letters when necessary. Be sure that the capitalization in the link matches the capitalization for the URL.

tip_4c.epsTo avoid problems with files on your website, follow a standard naming convention. Often, using only lowercase letters can simplify your life.

check Check the extension. Bios.htm and Bios.html are two different files. If your link's URL uses one extension and the actual filename uses another, your link won't work.

tip_4c.epsTo avoid problems with extensions on your website, pick either .html or .htm and stick to that extension.

check Check the filename. For example, bio.html and bios.html are two different files.

check Copy and paste. Avoid retyping a URL if you can copy it. The best and most foolproof way to create a URL that works is as follows:

a. Load a page in your browser.

b. Copy the URL from the browser’s address or link text box.

c. Paste the URL into your HTML markup.

The copy-and-paste method for grabbing URLs presumes that you're grabbing them from a website somewhere. If you open a local file on your PC in a browser, you see something that looks like this: file:///I:/H4D8e/html_letter.html. Here's how to decipher it:

check file:/// is a common browser convention used to identify the document as a file in your local file system. It's used in Internet Explorer, Chrome, Firefox, and Safari but not Opera (we checked): It uses localhost/C: for local filesystem and drive designations instead.

check I:/ is a drive letter.

check H4D8e/ is a folder or directory on that drive.

check html_letter.html — the rightmost text element, in this case — is the name of the HTML file you opened.

You can’t use URLs like this on a website, so please — don’t try to!

technicalstuff_4c.epsMost people have had at least one letter returned and marked undeliverable because of an incomplete or inaccurate address. When the address isn’t correct, the post office has no way to locate the intended recipient. The same is true for URLs. Without a fully formed URL, web servers don’t know how to locate the target web page. URLs generally take the following form:

check Protocol identifier followed by a colon (:) — This is generally either http for Hypertext Transport Protocol, https for secure-server sites, or ftp for file transfer sites.

check Hostname — This is generally either a domain name such as edtittel.com or an IP address. The hostname is always preceded by two slashes (//).

check Directory path — Directory paths are preceded by a forward slash (/), and they direct the user to the specific web page being sought.

Thus, a fully formed URL takes this general form: <protocolidentifier>://<hostname>/<directorypath>. And, for example, a fully formed URL is http://www.mywebsite.com/mywebpage.

Customizing Links

You can customize links to

check Open linked documents in new windows

check Link to specific locations within a web page of your own

check Link to items other than HTML pages, such as

• Portable Document Format (PDF) files

• Compressed files

• Word processing documents

Opening new windows

The web works because you can link pages on your website to pages on other people’s websites by using a simple anchor element. When you link to someone else’s site, though, you send users away from your own site.


The importance of http:// in HTML links

Browsers make surfing the web as easy as possible. If you type www.sun.com, sun.com, or often even just sun in your browser's address window, the browser obligingly brings up http://www.oracle.com/us/sun/index.html. Although this technique works when you type URLs into your browser window, it doesn't work when you're writing markup.

The URLs that you use in your HTML markup must be fully formed (complete in every detail). Browsers won't interpret URLs that don't include the page protocol. If you forget the http://, your link may not work!


To keep users on your site, HTML can open the linked page in a new window or in a new tab inside the same browser window. (Internet Explorer, Firefox, Chrome, and other browsers open new tabs. You can set Internet Explorer and other browser preferences to open in a new window instead of a new tab if you prefer.) The simple addition of the target attribute to an anchor element opens that link in a new browser window (or tab) instead of opening it in the current window:

<p>The <a href="http://www.w3.org" target="_blank">World Wide Web Consortium</a>

is the standards body that oversees the ongoing development of the XHTML

specification.</p>

When you give a target attribute a _blank value, this tells the browser to do the following:

1. Keep the linking page open in the current window.

2. Open the linked page in a new window or tab.

The result of using the target="_blank" attribute is shown in Figure 8-2, which depicts a new tab open for the W3C site.

9781118657201-fg0802

Figure 8-2: Use the target attribute to open a new Internet Explorer window or tab for a linked file.

warning_4c.epsPop-up windows irritate some users. Use them with care — and sparingly. You can use JavaScript to control the size, location, and appearance of pop-up windows as well as to put buttons on them to help users close them quickly. Check out Dr. Dobb’s article “Introduction to JavaScript Pop-up Windows” for all the details on how to manage window appearance, size, and position on the screen when it appears. Find it online at:

www.drdobbs.com/web-development/introduction-to-javascript-pop-up-window/184412937

Specifying locations in web pages

Locations within web pages can be marked for direct access by links on

check The same page.

check The same website.

check Other websites.

We discuss each method in upcoming sections.

Keep these considerations in mind when adding links to web pages:

check Several short pages may present information more conveniently for readers than one long page with internal links.

tip_4c.epsLinks within large pages work nicely for quick access to directories, tables of contents, and glossaries.

check Intradocument linking works best on your own website, where you can create and control the markup.

warning_4c.epsWhen you link to spots on someone else’s website, you’re at its manager’s mercy because that person controls linkable spots. Your links will break if a site designer removes or renames a spot to which you link.

Naming link locations

To identify and create a location within a page for direct access from other links, use an empty anchor element with the name attribute, like this:

<a name="top"></a>

The id attribute also works as an anchor element. It's often cleaner to use this method depending on your page design approach. (If you use id attributes for CSS, it may be easier to remember and more consistent overall.)

remember_4c.epsThe anchor element that marks the spot doesn’t affect the appearance of any surrounding content. You can mark spots wherever you need them without worrying about how your pages look (or change) as a result.

Linking within the same page

Links can help users navigate a single web page. Intradocument hyperlinks include such familiar features as

check Back to Top links.

check Tables of contents.

An intradocument hyperlink, also known as a named document link, uses a URL like this:

<a href="#top">Back to top</a>

technicalstuff_4c.epsThe pound sign (#) indicates that you're pointing to a spot on the same page, not on another page.

Listing 8-1 shows how two anchor elements combine to link to a spot on the same page. (Documents that use intradocument links are usually longer. This document is short so you can easily see how to use the top anchor element.)

Listing 8-1: Intradocument Hyperlinks

<!DOCTYPE html>

<html>

<head>

<title>Intradocument Hyperlinks at Work</title>

<meta charset="UTF-8">

</head>

<body>

<h1><a name="top"></a>Web-Based Training</h1>

<p>Given the importance of the Web to businesses and other organizations,

individuals who seek to improve job skills, or fulfill essential job

functions, are turning to HTML and XML for training, particularly to

HTML5. We believe this provides an outstanding opportunity for

participation in an active and lucrative adult and continuing education

market.</p>

<p><a href="#top">Back to top</a></p>

</body>

</html>

Figure 8-3 shows how this HTML markup appears in a web browser. If the user clicks the Back to Top link, the browser jumps back to the top spot — marked by <a name="top"></a>. The text for this example is short, but you can see how it works by resizing your browser window (making it tall and narrow) to display only two or three words per line of text.

9781118657201-fg0803

Figure 8-3: Use anchor elements to mark and link spots on a page.

Linking within the same website

You can combine intradocument and interdocument links to send visitors to a spot on a different web page on your site. Thus, to link to a spot named descriptions on a page named home.html on your site, use this markup:

<p>Review the <a href="home.html#descriptions">document descriptions</a>

to find the documentation for your particular product.</p>

Linking on other websites

If you know that a page on another site has spots marked, you can use an absolute URL to point to a particular spot on that page, like this:

<p>Find out how to

<a href="http://www.yourcompany.com/training/online.htm#register">

register</a> for upcoming training courses led by our instructors.</p>

remember_4c.epsBe sure to check all links regularly to catch and fix the broken ones.

Gizmodo updated its “Best Free Web Site Link Checker” article in April 2013, just as we were writing this book. You can find the article here:

www.techsupportalert.com/best-free-web-site-link-checker.htm

Linking to non-HTML resources

Links can connect to virtually any kind of file, such as the following:

check Word processing documents

check Spreadsheets

check PDFs

check Compressed files

check Multimedia

Two typical uses for non-HTML links are software and PDF download pages.

File downloads

Non-web files must nevertheless be accessed via the Internet, so they possess unique URLs, just like HTML pages. Any file on a web server (regardless of its type) can be linked using a URL.

For instance, if you want your users to download a PDF file named doc.pdf and a Zip archive called software.zip from a web page, you use this HTML:

<h1>Download the new version of our software</h1>

<p><a href="software.zip">Software</a></p>

<p><a href="doc.pdf">Documentation</a></p>

You can’t know how any user’s browser will respond to a click on a link that leads to a non-web file. The browser may

check Prompt the user to save the file.

check Display the file without downloading it (common for PDFs).

check Display an error message (if the browser can’t handle or doesn’t recognize the type of file involved).

tip_4c.epsBecause you can’t know how a browser will respond, help users download files successfully by providing

check As much information as possible about the file formats in use

check Any special tools they need to work with the files

Compressed files: To work with the contents of a Zip file, the users need a compression utility, such as WinZip or ZipIt, if their operating systems don’t support Zip files natively.

PDFs: To view a PDF file, users need the free Adobe Acrobat Reader (or some equivalent, such as Nitro PDF Reader).

You can make download markup more user-friendly by adding supporting text and links, like this:

<h1>Download our new software</h1>

<p> <a href="software.zip">Software</a> (1.2 MB compressed ZIP file)</p>

<p><b>Note:</b>

You need a zip utility such as

<a href="http://www.7-zip.org">7Zip</a> (Windows) or

<a href="http://www.maczipit.com">ZipIt</a> (Macintosh)

to open a ZIP file.</p>

<p><a href="doc.pdf">Documentation</a> (440 KB PDF file) </p>

<p><b>Note:</b>You need the free

<a href="http://get.adobe.com/reader/">Adobe Reader</a>

to view a PDF file.</p>

Figure 8-4 shows how a browser renders this HTML, and the dialog box it displays when you click the Software link.

9781118657201-fg0804

Figure 8-4: Chrome automatically downloads the Zip file.

E-mail addresses

A link to an e-mail address can automatically open a new e-mail addressed to exactly the right person.

tip_4c.epsThis is a great way to help users send you e-mail with comments and requests.

An e-mail link uses the standard anchor element and an href attribute. The value of the href attribute is the target e-mail address, prefaced with mailto:.

<p>Send us your

<a href="mailto:comments@mysite.com">comments</a>.</p>

The user’s browser configuration controls how the browser handles an e-mail link. Most browsers follow these two basic steps automatically:

1. Open a new message window in the default e-mail program.

2. Insert the address from the href attribute into the To field of the message.

tip_4c.epsUnfortunately, web page mailto: links are a prime source of e-mail addresses for spammers. Creating a form to receive feedback is often a better idea; better still, use JavaScript encryption on the e-mail address. (For more info, see Steven Chapman's great article "Hiding Your Email Address" at http://javascript.about.com/library/blemail1.htm.)

We generally tend to provide our e-mail addresses in the form: ed at edtittel dot com, knowing that people are smart enough to substitute @ for at and . for dot, and also knowing that address-harvesters usually aren't that canny. If you elect to use a form instead, be aware that this too can present security issues — always be sure to check your input, or take steps to avoid so-called SQL injection attacks. For more info, see Colin Mackay's article "SQL Injection Attacks and Some Tips on How to Prevent Them" atwww.codeproject.com/KB/database/SQLInjectionAttacks.aspx.

Media links

One of the very coolest features about HTML5 is its greatly enhanced capability to grab and play back or display media files inside your web browser. Earlier HTML and XHTML versions usually required a specific player program to grab and interpret media files, but HTML5 brings audio, video, and multimedia playback right into the browser. A series of W3C specifications describes how this all works:

check The <audio> element takes a URL that points to some kind of audio file as the value of its src attribute. See this page:

www.w3.org/TR/html5/embedded-content-0.html#audio

check The <video> element takes a URL that points to some kind of video file as the value for its src attribute. See this page:

www.w3.org/TR/html5/embedded-content-0.html#video

check The <source> element can take a URL that points to some type of media (src attribute) and to a related player or codec to interpret that media (type and media attributes). See this page:

www.w3.org/TR/html5/embedded-content-0.html#the-source-element