AskMe
AskMe

Reputation: 2561

access URL from button click in HTML

I have written the code like below:

<button class="btn post-btn">Read More &nbsp;
<a href="https://sway.office.com/iDYEqw?ref=Link"></a> 
<i class="fas fa-arrow-right"></i></button>

However, when i click the button, its redirecting to website.But the button image and text inside it is getting larger.

My Modified code:

<a href="https://sway.office.com/iDYEqw?ref=Link" class="btn post-btn">Read More &nbsp;</a> 
                            <i class="fas fa-arrow-right"></i></button>



enter code here

How to correct this? Thanks.

Upvotes: 0

Views: 467

Answers (2)

SMAKSS
SMAKSS

Reputation: 10520

This is not how the button works, you should either use <a> tag alone or create an onclick event for your button to do the redirect for you, or you can wrap your button inside a form and set the form action to your desired URL.

You can also wrap your button within a <a> which is not recommended at all, because according to W3C.org HTML docs it is not a standard way. A similar question about wrapping <button> inside <a> in SO.

  • Using <a> tag alone. Then you can style it like a button to make more sense.

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css" rel="stylesheet" />

<a href="https://sway.office.com/iDYEqw?ref=Link">Read More &nbsp;<i class="fas fa-arrow-right"></i></a>

  • Using <button> with onclick. Then you can redirect to your desired page with changing window.location.href value.

const button = document.querySelector("button");

button.addEventListener("click", function() {
  window.location.href = "https://sway.office.com/iDYEqw?ref=Link"
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css" rel="stylesheet" />

<button class="btn post-btn">Read More &nbsp;
<i class="fas fa-arrow-right"></i></button>

  • Wrap <button> inside the form. Then set the form action to your desired URL.

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css" rel="stylesheet" />

<form action="https://sway.office.com/iDYEqw?ref=Link" method="GET">
  <button>Read More &nbsp;<i class="fas fa-arrow-right"></i></button>
</form>

Upvotes: 2

Maimas2
Maimas2

Reputation: 961

This is a simple fix. You just have to put the button inside the a element, and a bit of CSS to make it look normal.:

a {
color: black;
text-decoration: none;
}
<a href="https://sway.office.com/iDYEqw?ref=Link">
  <button class="btn post-btn">Read More &nbsp;
</a> 
<i class="fas fa-arrow-right"></i></button>

Upvotes: 0

Related Questions