HTML button: go to another page - different approaches

There are several ways to create an HTML button to go to another page.

Method 1

<button id="btn_click">Click Me</button> <script> $('#btn_click').on('click', function() { window.location = 'http://www.google.com'; }); </script> 
  • Benefit: Separate JS from HTML (MVC)
  • Disadvantage: long codes, rely on JS
  • Note: jQuery selector is optional, can use traditional JavaScript

Method 2

 <button onclick="window.location='http://www.google.com'">Click Me</button> 
  • Advantage: 1-liner, no need to assign an identifier to a button
  • Downside: mix JS with HTML, rely on JS

Method 3

 <a class="click-me" href="http://www.google.com">Click me</a> <style> .clickMe { -moz-appearance: button; -ms-appearance: button; -o-appearance: button; -webkit-appearance: button; appearance: button; text-decoration: none; color: #000; padding: 0.2em 0.4em; }​ </style> 
  • Benefit: No need to rely on JS
  • Disadvantage: looks like a fake button, IE9 + required ( appearance - CSS3 property)
  • Note: this is from here

Method 4

 <form action="http://www.google.com"> <button>Click Me</button> </form> 
  • Advantage: the shortest code, no need to rely on JS
  • Disadvantage: improper use of the <form> . Doesn't work if there is a submit button

The programmers that are suitable are the most efficient (and therefore widely used), and why?

Note: can we do this as a wiki community?

+8
html button
source share
2 answers

I am making a link. A link is a link. The link will move to another page. This is what links are for and everyone understands it. So method 3 is the only correct method in my book.

I would not want my link to look like a button at all, and when I do this, I still think that functionality is more important than appearance.

Buttons are less accessible not only because of the need to use Javascript, but also because tools for the visually impaired may not well understand this improved Javascript button.

Method 4 will work, but this is more of a trick than real functionality. You are abusing the form to post "nothing" on this other page. He is not clean.

+4
source share

I use method 3 because it is most understandable to others (whenever you see the <a> tag, you know its link), and when you are part of a team, you have to do simple things;).

And finally, I don’t find it useful or effective to use JS just to go to another page.

+1
source share

All Articles