Skip to content Skip to sidebar Skip to footer

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 tw

Solution 1:

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

Solution 2:

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.

Solution 3:

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

2)<ahref="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>
...
functiondoSomething(elem){
//do something with url
returnfalse;//donotopen url
}

Post a Comment for "What's The Difference Between A Link Using Href And Onclick?"