TLDR; you can open an anchor link in a new Tab/Window but not a button.
Here is a rule of thumb:
For navigation just use anchor it's alright to style it as a button and let it use it's
href
attribute well.For quick actions (play,pause,stop,+1 like) just use button it doesn't have
href
for a reason!
Consider this code.
const [anchor] = document.getElementsByTagName('a')
const [button] = document.getElementsByTagName('button')
anchor.addEventListener('click', e => {
console.log('anchor clicked')
e.preventDefault()
}, false)
button.addEventListener('click', e => {
console.log('button clicked')
})
a {
text-decoration: none;
padding: 2px;
}
button {
background: none;
border: none;
font-size: 16px;
}
.btn {
background-color: blue;
color: white;
display: inline-block;
text-align: center;
}
<a class="btn" href="#">
Anchor
</a>
<hr/>
<button class="btn" type="button">
Button
</button>
Styling
They both look almost alike (with minimal justifications) the only problem is that you'll have to undo some stylings that come with button
like border
& background
but with anchor you don't get the clicking popping animation that you'd get with button.
Functionality
But since the anchors <a>
need <a href="some/path">
to work even if it's just #
, unless you need to navigate after clicking the anchor you'll have to use e.preventDefault()
in your javascript to prevent it.