Ballu Rocks
Ballu Rocks

Reputation: 1226

Onclick or href which is best for opening an link in button

Which is the best method.To open an link using button

<button type="button" onclick="location='permalink.php'">Permalink</button>

<button type="button" href="index.php">Permalink</button>

Upvotes: 2

Views: 24522

Answers (4)

LawMan
LawMan

Reputation: 3625

If you are using bootstrap, you can do this...

<a class="btn btn-default" href="permalink.php">Permalink</a>

Upvotes: 3

Vlad Balmos
Vlad Balmos

Reputation: 3412

If you use jquery you can write the second button like this

<button type="button" id="SecondButton" data-href="index.php">Permalink</button>

and then add some javascript:

<script type="text/javascript">
    $('#SecondButton').click(function(e) {
        e.preventDefault(); e.stopPropagation();
        window.location.href = $(e.currentTarget).data().href;
    });
</script>

Edit (Further completed scenarios)

<button type="button" id="SecondButton" data-href="index.php" onclick="location='permalink.php'" href="index.php">Permalink</button>

I would insert both additional href tag and onclick inside it too; you could then test for different scenarios; devices that do not support javascript or jquery fails to load on CDN like mobile etc:

<button type="button" id="SecondButton" data-href="index.php?trackAnalytics=1" onclick="location='permalink.php?trackAnalytics=2'" href="index.php?trackAnalytics=3">Permalink</button>

Upvotes: 4

c24w
c24w

Reputation: 7856

Alternatively, you can do something like this, if the button 'style' is what you're after, and not specifically the <button> tag:

<form method="link" action="permalink.php">
    <input type="submit" value="Permalink">
</form>

Another thought is that you could style an anchor to look like a button, then you could use the href attribute.

Upvotes: -1

Joseph
Joseph

Reputation: 119837

The first one should work, but inline scripts are not recommended. You should read about how to attach events using addEventListener for standards compliant browsers and attachEvent for older IE.

The second won't work since buttons don't use the href attribute.

Upvotes: 1

Related Questions