Jesús Rosas
Jesús Rosas

Reputation: 31

What's the difference between a link using href and onclick?

Everyone. I don't know much about programming and languages, I only have a few basics on HTML, so I hope someone could help me understanding the difference between the following two lines:

<a onclick="window.location.href='http://www.example.com'">Click here</a>

<a href="http://www.example.com">Click here</a>

Both seem to do the exact same thing, but I'm not sure if this is not true in all cases, i.e. using different browsers, HTML/HTML5, etc.

Any help would be appreciated. Thanks.

Upvotes: 3

Views: 2784

Answers (3)

aardrian
aardrian

Reputation: 9009

There many differences. Some of them relate to accessibility, some of them related to UX.

  • Without the href the browser will not style the link to look like a link (because it is not a link).
  • Without the href a link is not in the tab order of the page (for those who use keyboard to quickly traverse a page).
  • Without the href you are relying on JavaScript, which if there are errors elsewhere can become a problem.
  • It promotes using the <a> as a handler for something other than navigation, such as hiding/showing bits of the page, where a <button> would be more appropriate.
  • <a href> is supported by all browsers in all circumstances.
  • A screen reader may not announce a link without an href attribute, essentially making it unusable to many users (which has legal implications too).

Just use href as it will work everywhere and gets you accessibility for free.

Upvotes: 1

Alex Kudryashev
Alex Kudryashev

Reputation: 9460

1)<a onclick="window.location.href='http://www.example.com'">Click here</a>

2)<a href="http://www.example.com">Click here</a>

In this case there is not difference between the two provided the browser supports javascript and there is no JS errors on the page and in browser. But with onclick you can do something different with click. Example:

2)<a href="http://www.example.com" onclick="return doSomething(this)">Click here</a>
...
function doSomething(elem){
//do something with url
return false;//do not open url
}

Upvotes: 0

ddavison
ddavison

Reputation: 29032

the difference between the following two lines

The only difference is that you are using JavaScript to redirect rather than the built-in browser functionality.

See the W3C Specification for links

Upvotes: 4

Related Questions