How to create an HTML button that acts like a link

8,428,194

Solution 1

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.

Solution 2

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

Solution 3

If it's the visual appearance of a button you're looking for in a basic HTML anchor tag then you can use the Twitter Bootstrap framework to format any of the following common HTML type links/buttons to appear as a button. Please note the visual differences between version 2, 3 or 4 of the framework:

<a class="btn" href="">Link</a>
<button class="btn" type="submit">Button</button>
<input class="btn" type="button" value="Input">
<input class="btn" type="submit" value="Submit">

Bootstrap (v4) sample appearance:

Sample output of Boostrap v4 buttons

Bootstrap (v3) sample appearance:

Sample output of Boostrap v3 buttons

Bootstrap (v2) sample appearance:

Sample output of Boostrap v2 buttons

Solution 4

Use:

<a href="http://www.stackoverflow.com/">
    <button>Click me</button>
</a>

Unfortunately, this markup is no longer valid in HTML5 and will neither validate nor always work as potentially expected. Use another approach.

Solution 5

As of HTML5, buttons support the formaction attribute. Best of all, no JavaScript or trickery is needed.

<form>
  <button formaction="http://stackoverflow.com">Go to Stack Overflow!</button>
</form>

Caveats

  • Must be surrounded by <form> tags.
  • The <button> type must be "submit" (or unspecified) - I couldn't get it working with type "button." Which brings up the point below.
  • Overrides the default action in a form. In other words, if you do this inside another form it's going to cause a conflict.

Reference: formaction

Browser Support: <button>: The Button element

Share:
8,428,194
Mike
Author by

Mike

Updated on August 12, 2022

Comments

  • Mike
    Mike almost 2 years

    I would like to create an HTML button that acts like a link. So, when you click the button, it redirects to a page. I would like it to be as accessible as possible.

    I would also like it so there aren't any extra characters, or parameters in the URL.

    How can I achieve this?


    Based on the answers posted so far, I am currently doing this:

    <form method="get" action="/page2">
        <button type="submit">Continue</button>
    </form>
    

    but the problem with this is that in Safari and Internet Explorer, it adds a question mark character to the end of the URL. I need to find a solution that doesn't add any characters to the end of the URL.

    There are two other solutions to do this: Using JavaScript or styling a link to look like a button.

    Using JavaScript:

    <button onclick="window.location.href='/page2'">Continue</button>
    

    But this obviously requires JavaScript, and for that reason it is less accessible to screen readers. The point of a link is to go to another page. So trying to make a button act like a link is the wrong solution. My suggestion is that you should use a link and style it to look like a button.

    <a href="/link/to/page2">Continue</a>
    
    • redfox05
      redfox05 about 8 years
      Change GET to POST. Nobody seems to have addressed the OP's first problem, which was the ? on the URL. This is caused by the form being type="GET", change this to type="POST" and the ? at the end of the URL disappears. This is because GET sends all variables in the URL, hence the ?.
    • Nicolas Bouvrette
      Nicolas Bouvrette about 8 years
      @redfox05 This works in a context where you are not strict about which method you accept for your pages. In a context where you reject posts on pages that are expecting GET it will fail. I still think that using a link make sense with the caveat that it will not react to "spacebar" when active like button does. Also some style and behavior will be different (such as draggable). If you want the true "button-link" experience, having server side redirects for URL finishing by ? to remove it might be also an option.
    • snow
      snow over 7 years
      cssbuttongenerator.com might come in handy if you want to create a button with css.
    • yasar
      yasar almost 6 years
      I think it is better iade to create a link that looks like a button
    • Betlista
      Betlista over 5 years
      Just a note, for me "button acts like link" means, that I can do right-click and decide whether to open in new tab/window, which is not working with JS solutions...
    • David Spector
      David Spector about 3 years
      Form submission works even when JavaScript is turned off. And forms can act like Bootstrap columns or other styling, if you add class or style attributes to the button element. Is the trailing ? still a problem in 2021?
    • Varun Vejalla
      Varun Vejalla about 3 years
    • rjmunro
      rjmunro almost 3 years
      @redfox05 Changing a GET to a POST just to not have a ? on the URL is a terrible idea. GET means send me the information at this place, POST means something is being changed on the server. If you refresh a page after a POST, you get a warning. Caching is disabled. CDNs will behave differently. If you want something that "acts like a link", the correct solution is to use a link. You can then style the link or something inside it to look like a button. You could probably even put an actual <button> into the <a> tag.
    • mm4096
      mm4096 over 2 years
      You might want to avoid using a button as a link, as some browsers treat them differently. You can style a <a> to make it look like a button
    • Peter Mortensen
      Peter Mortensen over 2 years
      There are a lot of duplicate answers.
    • Peter Mortensen
      Peter Mortensen over 2 years
      For some reason, the cleanup of duplicate answers for this question is much more efficient (100 answers of which 59 are deleted (41 left)).
  • Admin
    Admin almost 14 years
    I think he is talking about not only functionality (click) but also appearance.
  • Pekka
    Pekka almost 14 years
    Simple and nice. A fine solution. Add display: inline to the form to keep the button in the flow.
  • Pekka
    Pekka almost 14 years
    @Web Logic yup, that's why I'm talking about styling the link to look like a button.
  • Pekka
    Pekka almost 14 years
    @Robusto that was a snarky comment about the empty space that used to be there :) This is not a good solution IMO, as it won't work without JavaScript.
  • Sean Patrick Floyd
    Sean Patrick Floyd almost 14 years
    @Pekka: yup, and also it's not even well-formed xhtml
  • Mike
    Mike almost 14 years
    in safari, this adds a question mark to the end of the url...is there a way to do it that doesn't add anything to the url?
  • Pekka
    Pekka almost 14 years
    @Andrew that is probably because of the GET method used by default by the form everywhere but in IE. You could switch the form method to POST but that would have other consequences, namely when you use the history to browse back after clicking the button. It may be unavoidable (it will have no effect anyway).
  • Benjamin Crouzier
    Benjamin Crouzier over 11 years
    Insn't it window.location.href='http://www.example.com' ? location.href doesn't seem to work for me in IE9...
  • Adam
    Adam over 11 years
    @pinouchon Should work. window is implied. Could be an IE9 bug, stackoverflow.com/questions/7690645/…
  • NimChimpsky
    NimChimpsky about 11 years
    if using form just use a submit, if using onclick why bother with the form. -1
  • lukeocom
    lukeocom over 10 years
    Keep in mind the spec says this is not valid as buttons should not contain any interactive descendants. w3.org/TR/2011/WD-html5-20110525/the-button-element.html
  • kenitech
    kenitech over 10 years
    It seems that if you don't specify type="button" this won't always work. Looks like the button will default to "submit"
  • Vladimir
    Vladimir over 10 years
    @BalusC Nice solution, but if it is inside some other form (parent form), then pressing this button redirects to address in the parent's form action attribute.
  • BalusC
    BalusC over 10 years
    @Wlad: nesting forms is illegal in HTML anyway. Browser's behavior is unspecified and should not be relied upon.
  • Sam Vloeberghs
    Sam Vloeberghs about 10 years
    @Wlad if you'd like this functionality, using a form, "inside" the form, keeping it "legal", you could place it outside the parent form and position it using css
  • Admin
    Admin about 10 years
    Is it just me or is the <button> tag missing an obvious href attribute?
  • bennos
    bennos almost 10 years
    If you want to open the link in a new window/tab use: onclick="window.open('example.com','_blank');"
  • Sam
    Sam almost 10 years
    I like to add style="cursor:pointer;" to make act like a link also.
  • Niels Keurentjes
    Niels Keurentjes almost 10 years
    @kenitech correct, according to specs: "The missing value default is the Submit Button state."
  • Peter Mortensen
    Peter Mortensen almost 10 years
    It is not well-formed HTML. The tag input does not have an ending tag.
  • ghoppe
    ghoppe almost 10 years
    @PeterMortensen According to the HTML spec, the input element is a void element. It must have a start tag but must not have an end tag.
  • Pekka
    Pekka almost 10 years
    @ChrisMarisic there's many downsides to using onClick: it doesn't work with JS turned off; the user can't open a link in a new tab/window, nor copy the link into their clipboard for sharing; parsers and bots won't be able to recognize and follow the link; browsers with a "prefetch" feature won't recognize the link; and many more.
  • Chris Marisic
    Chris Marisic almost 10 years
    While those are valid points, I don't really think that really address accessibility. Did you mean usability, not accessibility? In web development accessibility is usually reserved to be specifically about whether users who have visual impairments can operate your application well.
  • Blake A. Nichols
    Blake A. Nichols almost 10 years
    Set the button type="button", that will allow you to click it without submitting the form.
  • Irshu
    Irshu over 9 years
    but user cannot right click open in new tab, for that to work , u need the anchor tag
  • Admin
    Admin over 9 years
    @kenitech how to specify type="button"? I mean what object do you use? (input) ?
  • kenitech
    kenitech over 9 years
    @RehanMehdi This was a long time ago. I guess I was saying <input type="button" or something.
  • Arius
    Arius over 9 years
    Element 'button' cannot be nested within element 'a'.
  • Anders Martini
    Anders Martini over 9 years
    according to the standard no, But in my experience this works fine though. Haven't cross-browser tested it extensively yet, but at least FF and Chrome seem to handle it just fine, with expected behaviour.
  • Anders Martini
    Anders Martini over 9 years
    Arius: Read up a bit, experimented some more, and found that a button element can in fact be nested inside a <a> element, as long as the button element does not have its own action applied (since that would obviously result in a conflict - which action will the browser perform? the buttons or the <a>'s ?) but as long as you make sure the button-element itself doesn't trigger any action once clicked,this should work just fine (probably shouldn't be considered a best practice though)
  • Arius
    Arius over 9 years
    It's not about possibility. This is just against HTML5 specification and that's all.
  • birchbark
    birchbark over 9 years
    This will not work when the page your linking to already has get variables encoded in it (i.e. http://domain.com/search?query=test). Compound that with the fact that it will add a question mark and I really feel this should not be chosen as the correct answer -- it encourages people to use a hack that will eventually fail in edge cases.
  • Tejasvi Hegde
    Tejasvi Hegde over 9 years
    Looks simple and nice, but may have side effects if not considered properly. i.e. creating 2nd form in page, nested form etc.
  • BalusC
    BalusC over 9 years
    @Tejasvi: "Side effects"? Those things are just basic HTML mistakes. The HTML developer would then better take a step back and restart learning basic HTML.
  • Henry
    Henry over 9 years
    This is not really a great solution semantically. <a href=""> is the correct way to create a link. Plus you might run into some difficulty if your site is https and you're using this method to link to a non https page.
  • Hyder B.
    Hyder B. about 9 years
    While this works, it should not be considered as a solution but a workaround because if you pass this code through W3C validator, you will get errors.
  • scottkellum
    scottkellum about 9 years
    Seems a little overkill for styling a single button, no? With border, padding, background, and other CSS effects you can style buttons and links to look similar without bringing over an entire framework. The methodology Bootstrap uses is good, however using Bootstrap seems excessive.
  • Luca Detomi
    Luca Detomi over 8 years
    Just to complete information: formaction is compatible since "IE world" since version 10 and above
  • EternalHour
    EternalHour over 8 years
    @LucaDetomi - That is correct, however it is HTML5 specific. I've added another link with support data.
  • Mark Amery
    Mark Amery over 8 years
    Doesn't validate. Pasting into validator.w3.org/nu/#textarea gives Error: The element input must not appear as a descendant of the a element.
  • pseudosavant
    pseudosavant over 8 years
    @EternalHour Genuinely curious. In the examples you and I have provided is there supposed to be an appreciable difference between the behavior of those two forms? In this specific case does <button formaction> === <form action>?
  • EternalHour
    EternalHour over 8 years
    @pseudosavant - The difference is that your answer relies on Javascript in order to work. In this solution, no Javascript is needed, it's straight HTML.
  • pseudosavant
    pseudosavant over 8 years
    @EternalHour Sorry, I should have been more clear. Obviously the JS makes mine different but it is just a progressive enhancement. The form still goes to that link without the JS. I was curious about the intended behavior of just the HTML <form>s in each of our examples. Is formaction on a button supposed to add the ? to an empty GET submission? In this JSBin it looks like the HTML behaves exactly the same for both.
  • BoltClock
    BoltClock about 8 years
    @gerdi: Why would the href attribute make sense on the button element, let alone obviously so? A button is not a hyperlink. That said, perhaps XHTML 2 will be of interest to you...
  • Soren
    Soren about 8 years
    You actually get a reasonable button without any CSS at all
  • Victor
    Victor almost 8 years
    What if I want CTRL + Click to open the link in a new tab? This won't work with a button
  • Kiran Kotla
    Kiran Kotla over 7 years
    I'm not sure why this hasn't got more upvotes, to be honest. It works exactly as I need, and I did it this way because I wanted search engine spiders to be able to spot and follow the link. With JS that probably wouldn't have happened, and I'm not too sure of search engine behaviour when it comes to forms. It also doesn't result in any layout or behavioural side-effects (although I did assign a class to the anchor and set the text-decoration for that class to none).
  • Quentin
    Quentin over 7 years
    No, you can't. HTML forbids nesting <button> inside <a>.
  • Quentin
    Quentin over 7 years
    This is essentially the same as this answer from years earlier.
  • Uriahs Victor
    Uriahs Victor over 7 years
    If it forbids it then why does it work? :) No serious developer takes heed to everything W3C validator says...try passing Facebook or Google or any huge website through there...The web isn't waiting for anyone
  • hbulens
    hbulens about 7 years
    If you want to open the uri in a new tab, you should add formtarget="_blank" to the button.
  • Jacob
    Jacob almost 7 years
    @UriahsVictor It may work today, but one day browser vendors may decide to change the behavior as it isn't valid.
  • Uriahs Victor
    Uriahs Victor almost 7 years
    @JacobAlvarez browser maintainers know better. This isn't something uncommon, they wouldn't want to go down as the browser which broke the internet.
  • Jacob
    Jacob almost 7 years
    @UriahsVictor Flash and Java applets were pretty common too.
  • Adsy2010
    Adsy2010 almost 7 years
    Its useful to note that this only works when wrapped by form tags. Found that out the hard way...
  • Lucian Minea
    Lucian Minea almost 7 years
    Yes, Hyder B. you're right, but one you also should keep in mind that the standards are only raw guides. As a programmer you should always think outside the box and try things that are not in the book ;) .
  • Zeek2
    Zeek2 almost 7 years
    FYI HTML also forbids the opposite (according to VS2015): nesting <a> inside <button> but that also works on: IE11, Edge, Firefox, Chrome and Safari and some/all mobile browsers.
  • Zeek2
    Zeek2 almost 7 years
    Both of you are correct. VS2015 flags this with a warning: "Element 'a' cannot be nested inside element 'button'" but it works with: IE11, Edge, Chrome, Firefox, Safari and at least some (perhaps all) mobile browsers currently. So don't use this technique but if you did in the past, it works for now ;)
  • EternalHour
    EternalHour over 6 years
    @Adsy2010 - Yeah unfortunately, that's why I put them there. I did add some additional information to the answer that specifies that.
  • Brambor
    Brambor over 6 years
    I used that but in the end I had to copy all button attributes to this class so that the button looks exactly the same. Without it text of the button barely fit within the button borders.
  • Muhammad Omer Aslam
    Muhammad Omer Aslam over 6 years
    this would only mimic opening the link in the target window rather than target blank
  • Navin
    Navin about 6 years
    Please don't do this. It breaks so many things such as the right-click context menu for links.
  • Damian Green
    Damian Green almost 6 years
    Note that the "location.href" part is simply JS. It resets the "window" object to have a new location with an href of whatever. Thus you could use other JS commands here as well, for instance, if you wanted to open the link in a new tab, you could use: <button type="button" onclick="window.open('https://....', '_blank');">.
  • Katinka Hesselink
    Katinka Hesselink over 5 years
    Just to let readers know: this DOES work in IE11, when using html5 and an enclosing form tag.
  • Spongman
    Spongman over 5 years
    unfortunately, doesn't work when formaction='#anchor'.
  • sijones
    sijones over 5 years
    this seems to work:<a href="w3schools.com"> <button> Button </button> </a>
  • Admin
    Admin over 5 years
    Interesting fact: You can have multiple buttons (and multiple urls) inside the form tags :)
  • Roko C. Buljan
    Roko C. Buljan over 4 years
    NEVER wrap other anchors or form-action elements into Anchor.
  • Lucian Minea
    Lucian Minea over 4 years
    Aha, and why is that ?
  • compski
    compski over 4 years
    Unfortunately the Company Outlook blocks the button unless you press additional step "View in Browser". Any ideas how to get around that?
  • Stephen R
    Stephen R over 4 years
    You should use <button type="button">... so that it doesn't by default function as a Submit
  • Stephen R
    Stephen R over 4 years
    Only if you want it to reset your form. Use type="button"
  • Adam Hey
    Adam Hey about 4 years
    Why would you have a form submit approach just for navigation?? Ridiculous
  • corn on the cob
    corn on the cob almost 4 years
    You'll need some kind of https:// or http:// before the URL though. You can also link to local files using file:///
  • Lucretiel
    Lucretiel almost 4 years
    The problem is the "A that looks like a button" is that it doesn't automatically respond to the enter key, right? @AdamHey perhaps because the destination of the link is dynamic based on the content of the form?
  • Tim Daubenschütz
    Tim Daubenschütz over 3 years
    The problem with the HTML example is that when query params are added, form will not respect them and proceed without as technically they will have to be <input>s within the <form>.
  • Timo
    Timo over 3 years
    type=button does not seem to be relevant any more.
  • MonkeyVoodoo
    MonkeyVoodoo about 3 years
    You should reconsider why and if you need a button in your design. If really necessary, you can style anchor elements to look like a button really quickly, no need for bootstrap.
  • BalusC
    BalusC about 3 years
    @MonkeyVoodoo: indeed.
  • Peter Mortensen
    Peter Mortensen about 3 years
    Does this work with current (2021) browsers?
  • Peter Mortensen
    Peter Mortensen about 3 years
    Why is it different using an SSL certificate?
  • Peter Mortensen
    Peter Mortensen about 3 years
    An explanation would be in order.
  • Peter Mortensen
    Peter Mortensen about 3 years
    How is this different from previous answers (not a rhetorical question)?
  • Anders Martini
    Anders Martini almost 3 years
    @PeterMortense I haven't got a clue to be honest, I'm not doing much frontend work these days. shouldn't be too hard to find out though, just make a html document and try! :)
  • jdh8
    jdh8 almost 3 years
    The button outside of the text does not link.
  • isherwood
    isherwood almost 3 years
    This is invalid HTML.
  • isherwood
    isherwood almost 3 years
    I'm not sure what needs to be explained. This is the right element for navigation, and styling is at the developer's discretion.
  • Someone_who_likes_SE
    Someone_who_likes_SE almost 3 years
    button element should NEVER be inside a elements.
  • General Grievance
    General Grievance over 2 years
    Please do not add duplicate answers. This answer has already covered using anchor in button: stackoverflow.com/questions/2906582/….
  • viveknaskar
    viveknaskar over 2 years
    This is the key. Adding type="button" was the key for me.
  • Someone_who_likes_SE
    Someone_who_likes_SE over 2 years
    The validation says a link should never be inside a button.
  • Peter Mortensen
    Peter Mortensen over 2 years
    This looks deceptively simple after 11 years and 63 answers (incl. deleted answers). I think extraordinary simple solutions require extraordinary explanations. Why would this work? Under what conditions (considering it apparently does not pass HTML validation)? The question included "page2" in the link. How does this match the question? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
  • Peter Mortensen
    Peter Mortensen over 2 years
    This is a duplicate of at least two answers, Sense of Science's answer and neevjs's answer (they may themselves both be duplicate answers).
  • Peter Mortensen
    Peter Mortensen over 2 years
    The oldest answer this is a duplicate of is lukeocom's answer.
  • Peter Mortensen
    Peter Mortensen over 2 years
    This is a duplicate of lukeocom's answer.
  • Peter Mortensen
    Peter Mortensen over 2 years
    This is a duplicate of lukeocom's answer.
  • Peter Mortensen
    Peter Mortensen over 2 years
    Can you address the alleged failure to pass HTML validation in your answer? Please respond by changing your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
  • baash05
    baash05 over 2 years
    the only issue with this is inline JS is considered bad form and sometimes violates CSP's
  • thedebuggger
    thedebuggger over 2 years
    thank you so much for this simple answer.
  • brennanyoung
    brennanyoung over 2 years
    There's a very good reason this is not valid code: Accessibility. Tab stops (e.g. links) should not contain tab stops (e.g. buttons) because Assistive Tech (screen readers etc.) do not know how to present them to the user. Ask yourself: Which one gets keyboard focus via tabbing? Which one is supposed to handle the click event? So, besides failing the HTML validator, you'll also violate WCAG, which can have legal consequences - a box which it is wiser not to think too far outside of.
  • can.do
    can.do about 2 years
    Right answer! Simple 1-liner that works. Just use 1 of the onclick= options. HTML anchor tag isn't valid, suggest taking it out.
  • rlatief
    rlatief almost 2 years
    Accessibility speaking, which one do you think is better between the form and the JS one?
  • user229044
    user229044 almost 2 years
    This assumes both Bootstrap and FontAwesome, neither of which are mentioned in the question.