How to Create an HTML Button that Acts Like a Link

W3docs
2 min readNov 18, 2019

--

Sometimes we need to create an HTML button, that acts like a link (i.e., clicking on it the user is redirected to the specified URL).

There are some methods, we are going to present 3 of them. Choose one of the following methods to add a link to an HTML button.

All right. Let’s go!

1. Add inline onclick event

a) To HTML <button> tag within HTML <form> element.

Example

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<button onclick="window.location.href = 'https://w3docs.com';">Click Here</button>
</body>
</html>

Try it yourself

It might not work if the button is inside a <form> tag.

b) To <input> tag within HTML <form> element.

Example

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<form>
<input type="button" onclick="window.location.href = 'https://www.w3docs.com';" value="w3docs"/>
</form>
</body>
</html>

Try it yourself

The links won’t work when JavaScript is disabled, and search engines may ignore such kind of links.

2. Use action or formaction attributes within <form> element

a) Action attribute

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<form action="https://www.w3docs.com/">
<button type="submit">Click me</button>
</form>
</body>
</html>

Try it yourself

To open the link in a new tab add attribute target=”_blank”.

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<form action="https://www.w3docs.com/" method="get" target="_blank">
<button type="submit">Click me</button>
</form>
</body>
</html>

Try it yourself

As there is no form and no data is submitted, this may be semantically incorrect. However, this markup is valid.

b) HTML5 formaction attribute.

Example

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<form>
<button type="submit" formaction="https://www.w3docs.com">Click me</button>
</form>
</body>
</html>

Try it yourself

The formaction attribute is only used for buttons with type=”submit”. As this attribute is HTML5-specific, support in old browsers might be poor.

3. Add a link styled as an HTML button (using CSS)

Example

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.button {
background-color: #1c87c9;
border: none;
color: white;
padding: 20px 34px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 20px;
margin: 4px 2px;
cursor: pointer;
}
</style>
</head>
<body>
<a href="https://www.w3docs.com/" class="button">Click Here</a>
</body>
</html>

Try it yourself

As complex styling is required, this may not work on specific browsers.

--

--

W3docs

W3docs provides free learning materials for programming languages like HTML, CSS, Java Script, PHP etc.