Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.location.href vs clicking on an Anchor

Tags:

What's the difference between clicking on:

<a href /> 

vs.

calling window.location.href = ...

?

like image 348
LB. Avatar asked Nov 03 '09 13:11

LB.


People also ask

What can I use instead of window location href?

Location assign() Method location. replace("http://someUrl.com");

Is href required for anchor?

All attributes are optional, although one of NAME and HREF is necessary for the anchor to be useful.


2 Answers

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!
like image 52
nickf Avatar answered Sep 19 '22 13:09

nickf


Setting window.location.href = 'thepage.html' is the same as calling:

window.open('thepage.html', '_self'); 

I.e. the target is limited to the same window, as that is where the location property is. This has the same effect as clicking a link without a target attribute:

<a href="thepage.html">...</a> 

You can use the open method instead to specify a different target, like a new window:

window.open('thepage.html', '_blank'); 

This has the same effect as clicking a link with that target:

<a href="thepage.html" target="_blank">...</a> 

You can also use the open method to open a new window. The return value is a reference to the window, so you can use that to set the location of that window instead of the current window:

var w = window.open('about:blank', '_blank'); w.location.href = 'thepage.html'; 
like image 23
Guffa Avatar answered Sep 18 '22 13:09

Guffa