Sam Becker
Sam Becker

Reputation: 19646

What are the best practices for creating linked markup in HTML documents?

I have seen a few different ways of creating clickable regions or groups of elements in HTML documents.

One method is to wrap a bunch of elements in an anchor tag and make it display block. Some argue however that this is semantically incorrect. Another way is to use JavaScript, however when not done carefully it can ruin user experience by disabling middle click and right click.

Upvotes: 1

Views: 145

Answers (1)

bchociej
bchociej

Reputation: 1399

W3 say:

(Edit: a link would be nice... dev.w3.org)

The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links). This example shows how this can be used to make an entire advertising block into a link:

<aside class="advertising">
 <h1>Advertising</h1>
 <a href="http://ad.example.com/?adid=1929&amp;pubid=1422">
  <section>
       <h1>Mellblomatic 9000!</h1>
   <p>Turn all your widgets into mellbloms!</p>
   <p>Only $9.99 plus shipping and handling.</p>
  </section>
 </a>
 <a href="http://ad.example.com/?adid=375&amp;pubid=1422">
  <section>
   <h1>The Mellblom Browser</h1>
   <p>Web browsing at the speed of light.</p>
   <p>No other browser goes faster!</p>
  </section>
 </a>
</aside>

So, if you have no interactive content, use <a>; otherwise, use JavaScript. That's my take, anyway.

Additionally, I'd also assert that, because <a> has text-level semantics, anything that isn't text-like should be made clickable with JavaScript instead of <a>. That said, plenty of folks write e.g. <a href="..."><img ...></a>, and images surely aren't text-like. So it's a murky topic at best.

Upvotes: 1

Related Questions