adplus-dvertising

How do I create an HTML button that acts like a link?

Asked 12 years ago
Viewed 8.58 k times

How do I create an HTML button that acts like a link? So that clicking the button redirects the user to a page.

I want it to be accessible, and with minimal extra characters or parameters in the URL.

asked 12 years ago

Correct Answer

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.

answered 5 months ago

Other Answer

<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.

answered 12 years ago