Home

Published

- 3 min read

HTML 5: When to use <a> or <button>

img of HTML 5: When to use <a> or <button>

tl:dr

  • Use <a> for page navigation
  • Use <button> for actions on the page
  • Use <input type="button" /> in a form

The Problem

Consider the following code:

<a id="btn" class="btn btn-default">Button</a>
<script>
	var btn = document.getElementById('btn')
	btn.addEventListener('click', function (e) {
		e.preventDefault()
		console.log('awesome btn action')
	})
</script>

While some might say this is a perfectly fine way to define a button, closer inspection reveals a few problems:

First, you would notice that hovering over the button you get a text cursor instead of a ‘hand’-cursor. This is caused by leaving the attribute “href” undefined, you can fix it via defining something like ’#’ or via CSS.

Then you would notice that by defining the “href” tag you would cause the browser to navigate to another page or the top of the page. To prevent this you would then need to add some Javascript code and call ‘event.preventDefault()’, or add to your previous hack and define the href as ‘#0’. This solves the problem by relying on the browser not knowing what to do with illegal element ids (ids can never start with a number).

Voila, you are now in the situation that you are using some hack pattern that degrades the readability of your code. Someone may come along and assume that someone made a mistake defining the href attribute /or used a placeholder and forgot to replace it.

The Solution

Now let’s improve the readability of the code:

<button id="btn" class="btn btn-default" type="button">Button</button>
<script>
	var btn = document.getElementById('btn')
	btn.addEventListener('click', function () {
		console.log('awesome btn action')
	})
</script>

By using the correct tag <button>, you eliminate the need for any workarounds to fix the cursor or odd href and save yourself a line of Javascript. Although you’ll still need CSS to make the button look consistent across browsers, which you would likely have used for styling the <a> button as well.

But what about IE8? - for that we set the type=‘button’, and IE8 is almost of no concern anymore (even for big corporate customers)

<button> vs <input type="button" />

Both types of buttons work in practice the same way. However, the Button element allows you to add content elements, like an image. And usually, you would use the <input type="text" /> tag in a </button> <form>.

As we are not working with a form and just want to have a button to execute some JS-Code I would use the Button tag.

Summary

  • <a> is used for page navigation
  • <button type="button"> is used for actions on the page, can contain other HTML elements
  • <input type="button" /> is used in a form

Some More Reading

images: [”../../../assets/images/Designed by Freepik”]