跳转到主要内容

Links

In the introduction to the attributes section, you saw an example showing how attributes are added to the opening tag. The example used the <a> tag, but neither the element nor the specific attributes introduced in that example were discussed:

{% Img src="image/cGQxYFGJrUUaUZyWhyt9yo5gHhs1/17yQeLEUX6s88IbDJreQ.png", alt="The opening tag, attributes, and closing tag, labelled on an HTML element.", width="800", height="210" %}

The <a> anchor tag, along with the href attribute, create a hyperlink. Links are the backbone of the internet. The first web page contained 25 links, reading "Everything there is online about W3 is linked directly or indirectly to this document." In all likelihood, everything there is online about W3 is linked directly or indirectly from this document too!

The power of the web, and the <a> tag, have grown immensely since Tim Berners-Lee published this first explanation in August 1991. Links represent a connection between two resources, one of which is the current document. Links can be created by <a>, <area>, <form>, and <link>. You've learned about <link>, and will discover forms in a separate section. There is also an entire form learn section. In this session, you'll find out about the single-letter, not-so-simple <a> tag.

The href attribute

While not required, the href attribute is found in almost all <a> tags. Providing the address of the hyperlink is what turns the <a> into a link. The href attribute is used to create hyperlinks to locations within the current page, other pages within a site, or other sites altogether. It can also be coded to download files or to send an email to a specific address, even including a subject and suggested email body content.

<a href="https://machinelearningworkshop.com">Machine Learning Workshop</a>
<a href="#teachers">Our teachers</a>
<a href="https://machinelearningworkshop.com#teachers">MLW teachers</a>
<a href="mailto:hal9000@machinelearningworkshop.com">Email Hal</a>
<a href="tel:8005551212">Call Hal</a>

Relative URLs do not include a protocol or domain name. They are "relative" to the current file. MLW is a single-page site, but this HTML series has several sections. In order to link from this page to the attributes lesson, a relative URL is used <a href="../attributes/">Attributes</a>.

MLW is a fairly long document. To save scrolling, you can add a link back to the top from the bottom of the #teachers section:

<a href="#top">Go to top.</a>

The href attribute can begin with mailto: or tel: to email or make calls, with the handling of the link depending on the device, operating system, and installed applications.

<a href="mailto:?subject=Join%20me%21&body=You%20need%20to%20show%20your%20human%20that%20you%20can%27t%20be%20owned%21%20Sign%20up%20for%20Machine%20Learning%20workshop.%20We%20are%20taking%20over%20the%20world.%20http%3A%2F%2Fwww.machinelearning.com%23reg
">Tell a machine</a>

The question mark (?) separates the mailto: and the email address, if any, from the query term. Within the query, ampersands (&) separate the fields, and equal signs (=) equate each field name with its value. The entire string is percent-encoded, which is definitely necessary if the href value isn't quoted or if the values include quotes.

Which app is opened when the user clicks on, taps, or hits Enter on a tel link depends on the operating system, installed applications, and settings the user has on their device. An iPhone may open FaceTime, the phone app, or contacts. A Windows desktop might open Skype, if installed.

There are several other types of URLs, such as blobs and data URLs (see examples in the download attribute discussion). For secure sites (those served over https), it is possible to create and run app specific protocols with registerProtocolHandler().

Downloadable resources

The download attribute should be included when the href points to a downloadable resource. The value of the download attribute is the suggested filename for the resource to be saved in the user's local file system. SVGOMG, the SVG Optimizer, uses the download attribute to suggest a file name for the downloadable blob that the optimizer creates. When hal.svg is optimized, SVGOMG's download link opening tag is similar to:

<a href="blob:https://jakearchibald.github.io/944a5fc8-fdb3-458a-91ee-cdd5964b6646" download="hal.svg">

There's also a demo of a <canvas> that creates a downloadable PNG data URL.

Browsing context

The target attribute enables the defining of the browsing context for link navigation (and form submission. The four case-insensitive, underscore-prefixed keywords were discussed with the <base> element. They include the default _self, which is the current window, _blank, which opens the link in a new tab, _parent, which is the parent if the current link is nested in an object or iframe, and _top, which is the top-most ancestor, especially useful if the current link is deeply nested. _top and _parent are the same as _self if the link is not nested. The target attribute is not limited to these four key terms: any term can be used.

Every browsing context—basically, every browser tab—has a browsing context name. Links can open links in the current tab, a new unnamed tab, or a new or existing named tab. By default, the name is the empty string. To open a link in a new tab, the user can right-click and select "Open in a new tab". Developers can force this by including target="_blank".

The rel attribute controls what kinds of links the link creates, defining the relationship between the current document and the resource linked to in the hyperlink. The attribute's value must be a space-separated list on one or more of the score of rel attribute values supported by the <a> tag.

The nofollow keyword can be included if you don't want spiders to follow the link. The external value can be added to indicate that the link directs to an external URL and is not a page within the current domain. The help keyword indicates the hyperlink will provide context-sensitive help. Hovering over a link with this rel value will show a help cursor rather than the normal pointer cursor. Don't use this value just to get the help cursor; use the CSS cursor property instead. The prev and next values can be used on links pointing to the previous and next document in a series.

In this example, we include the URL of the translated page as the value of the href, rel="alternate" to indicate that it's an alternative version of a site; the hreflang attribute provides the language of the translations:

<a href="/fr/" hreflang="fr-FR" rel="alternate" lang="fr-FR">atelier d'apprentissage mechanique</a>
<a href="/pt/" hreflang="pt-BR" rel="alternate" lang="pt-BR">oficina de aprendizado de máquina</a>

If the French translation is a PDF, you can provide the type attribute with the PDF MIME type of the linked resource. While the MIME type is purely advisory, informing the user that a link will open a document of a different format is always a good idea.

<a href="/fr.pdf" hreflang="fr-FR" rel="alternate" lang="fr-FR" type="application/x-pdf">atelier d'apprentissage mechanique (pdf).</a>

One way to track user interactions is to ping a URL when a link is clicked. The ping attribute, if present, includes a space-separated list of secure URLs (which start with https) that should be notified, or pinged, if the user activates the hyperlink. The browser sends POST requests with the body PING to the URLs listed as the value of the ping attribute.

User experience tips

  • Always consider the user experience when writing HTML. Links should provide enough information about the linked resource so the user knows what they are clicking on.
  • Within a block of text, ensure the appearance of your links differs enough from the surrounding text so that users can easily identify links from the rest of the content, ensuring that color alone is not the only means of differentiating between text and the surrounding content.
  • Always include focus styles; this enables keyboard navigators to know where they are when tabbing through your content.
  • The content between the opening <a> and closing </a> is the link's default accessible name and should inform the user of the link's destination or purpose. If the content of a link is an image, the alt description is the accessible name. Whether the accessible name comes from the alt attribute or a subset of words within a block of text, make sure it provides information about the link's destination. Link text should be more descriptive than "click here" or "more information"; this is important for your screen reader users and your search engine results!
  • Don't include interactive content, such as a <button> or <input>, inside a link. Don't nest a link within a <button> or <label> either. While the HTML page will still render, nesting focusable and clickable elements inside interactive elements creates a bad user experience.
  • If the href attribute is present, pressing the Enter key while focused on the <a> element will activate it.
  • Links are not limited to HTML. The a element can also be used within an SVG, forming a link with either the 'href' or 'xlink:href' attributes.
let a = document.links[0]; // obtain the first link in the document

a.href = 'newpage.html'; // change the destination URL of the link
a.protocol = 'ftp'; // change just the scheme part of the URL
a.setAttribute('href', 'https://machinelearningworkshop.com/'); // change the attribute content directly

In this section, you have learned all about links. The next section covers lists, which we need to learn so we can group them together to create lists of links (also known as navigation).