How to create an HTML button that acts like a link?
<button onclick="location.href='http://www.example.com'" type="button">
www.example.com</button>
Note that the type="button"
attribute is important, since its missing value default is the Submit Button state.
HTML
The plain HTML way is to put it in a <form>
wherein you specify the desired target URL in the action
attribute.
<form action="https://google.com">
<input type="submit" value="Go to Google" />
</form>
If necessary, set CSS display: inline;
on the form to keep it in the flow with the surrounding text. Instead of <input type="submit">
in above example, you can also use <button type="submit">
. The only difference is that the <button>
element allows children.
You'd intuitively expect to be able to use <button href="https://google.com">
analogous with the <a>
element, but unfortunately no, this attribute does not exist according to HTML specification.
CSS
If CSS is allowed, simply use an <a>
which you style to look like a button using among others the appearance
property (it's only not supported in Internet Explorer).
a.button {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
text-decoration: none;
color: initial;
}
<a href="https://google.com" class="button">Go to Google</a>
Or pick one of those many CSS libraries like Bootstrap.
<a href="https://google.com" class="btn btn-primary">Go to Google</a>
JavaScript
If JavaScript is allowed, set the window.location.href
.
<input type="button" onclick="location.href='https://google.com';" value="Go to Google" />
Instead of <input type="button">
in above example, you can also use <button>
. The only difference is that the <button>
element allows children.