Search code examples
javascripthtmlonclickhref

HTML href=" " vs onclick="self.location.href=' ' "


I came across this JS code:

onClick="self.location.href='http://stackoverflow.com/'"

I have used this in my website and it has the same function like the href attribute.

I am new in JS and I do not know much about JS, but there may be a difference between the onclick="self.location.href=''" and href="" attribute.

What is the difference?

What are the benefits and what are the disadvantages?


Solution

  • The first benefit of using href tag would be for the search engines. Most of the search engines detect href attribute and crawl your website, the other thing would be if the user disabled their javascript in their browser, self.location.href wont work. But the href attribute only works with the a tag, so when you want to redirect a user when clicking on a button for example, you can not use href attribute as button tag or input tag wont accept href attribute, so you should use window.location or self.location