If you are making some web application and you need to redirect user to another page, you can create a button that will act link a link.
Regular <a href="#"> tag may not be suitable in some cases, for example, when you have complex logic or unusual content on a form.
Each example given below is wrapped with the standard HTML5 template code. This will allow you to test the functionality immediately if you save the specific demo into file.
In a first example, the regular button element is used with the onclick attribute set to custom code that assigns href property of the location object. Once clicked, the browser will redirect a user to the specified URL address.
<!DOCTYPE html> <html> <head> <title>Web Application</title> </head> <body> <button onclick="window.location.href='https://example.com';"> Visit Site </button> </body> </html>
<!DOCTYPE html> <html> <head> <title>Web Application</title> </head> <body> <form> <input type="button" onclick="window.location.href='https://example.com';" value="Visit Site" /> </form> </body> </html>
The following example is completely different from what you have seen above. The button element is wrapped with the form element, which has the action property set to the desired URL.
It's important to note the the button must have the type property set to the "submit" string, this will instruct the browser to submit form to the server.
<!DOCTYPE html> <html> <head> <title>Web Application</title> </head> <body> <form action="https://example.com" method="get"> <button type="submit">Visit Site</button> </form> </body> </html>
The following code block is very similar to the previous, there is a form with the nested button of the "submit" type. But the URL is set directly in the formaction attribute of the button tag, such a setting will override actions set directly on the form tag.
<!DOCTYPE html> <html> <head> <title>Web Application</title> </head> <body> <form> <button type="submit" formaction="https://example.com">Visit Site</button> </form> </body> </html>
In most of the cases, overriding standard browser functionality is not a good practice. If the page contains a form, then it should work as expected by the user, also the links should work in the same manner. Users should not be distracted or confused by the unusual web application design.
This means that if you do add a button that acts like a link, you must be confident that such a functionality is a benefit for the users.
Thank you for reading this article. Please do not hesitate to leave your comments in the form below, your feedback on the topic described in this article is highly appreciated.