Skip to content Skip to sidebar Skip to footer

Window.location.href Vs Clicking On An Anchor

What's the difference between clicking on: vs. calling window.location.href = ... ?

Solution 1:

Wherever possible, you should use <a href="foo.html"> over window.location.href, for a number of very good reasons.

  1. If you have javascript disabled, none of the links would work.
  2. Spiders, such as Google Bot, do not interpret javascript, and so they won't follow any of your links.
  3. IT BREAKS THE INTERNET. No, really though - the World Wide Web is built on the very basis of discoverable linkages between pages. Hiding these linkages with non-standard .. err, links, goes against that very premise.
  4. It makes for a bad user experience: a user expects that when they mouse over a link, they will have access to some information:
    • the destination displayed in the status bar (very important!)
    • right-click -> copy link location
    • middle-click -> open new tab
    • etc
    • Using window.location breaks all of these
  5. It's much easier!

Solution 2:


Solution 3:

Don't forget that in addition to the above answers, clicking on a hyperlink (anchor tag) will trigger that element's onclick handler (if any), whereas the Javascript version clearly doesn't and just changes the window's location.

It is possible to manually invoke the onclick handler from Javascript if you want to simulate a click, but you must remember to do this manually. The snippets you posted would differ in this regard, which could be the cause of any behavioural differences.


Solution 4:

With the anchor you can specify the target property, but with window.location.href you can't. Generally the anchor is used when a user wants to redirect the browser to another location, window.location.href is used when the redirection is done using javascript.


Solution 5:

In addition to the other answers given, clicking on an <a> element with the href attribute sapecified will cause the browser to navigate to the URL in the href, regardless of whether JavaScript is enabled or not.


Post a Comment for "Window.location.href Vs Clicking On An Anchor"