Table of Contents
For one reason or another, you might want to create a button in HTML that functions like a normal link.
This can be useful in call-to-action buttons or other situations where you don't want to directly use an anchor tag.
In this post, we'll explore the few ways in which you can create a button link in HTML.
Using onclick events on Buttons
The first way to create a button link is to use the onclick attribute on a button tag.
This attribute defines the code that will execute once this element is clicked.
You can combine this with the fact that window.location.href will redirect the user to a new page, and put that inside your attribute.
Here's an example of that:
HTML<button onclick="window.location.href = 'https://sabe.io'">
Go to Sabe.io
</button>
Clicking on the button will redirect the user to Sabe.io.
Using onclick events on Inputs
Instead of using buttons, you can also use input tags to accomplish the same thing.
Simply add your onclick attribute to the input tag, and nest it inside a form tag and it should work in the same manner:
HTML<form>
<button onclick="window.location.href = 'https://sabe.io'">
Go to Sabe.io
</button>
</form>
Using action on forms
Keeping in line with form elements, you can also use the action attribute on a form tag to send the user to a new page.
HTML<form action="https://sabe.io" method="get">
<button type="submit">
Go to Sabe.io
</button>
</form>
When you submit this form, the browser will send the user to Sabe.io since that's what the action attribute is set to. If you want to open it in a new tab, you can use the target attribute and set it to _blank.
HTML<form action="https://sabe.io" method="get" target="_blank">
<button type="submit">
Go to Sabe.io
</button>
</form>
Conclusion
In this post, we saw several ways in which you can create a button link in HTML without needing to use an anchor tag.
This is useful in the scenarios where you don't want to directly use an anchor tag.
Thanks for reading!
Getting Started with Svelte
Getting Started with Express
Git Tutorial: Learn how to use Version Control
How to Serve Static Files with Nginx and Docker
How to Set Up Cron Jobs in Linux
How to deploy a Deno app using Docker
How to deploy an Express app using Docker
Learn how to use v-model with a custom Vue component
Using Puppeteer and Jest for End-to-End Testing
Getting Started with Moment.js
Getting Started with Vuex: Managing State in Vue
Setting Up a Local Web Server using Node.js
