javascript - Creating links without actually putting the whole link in <a> tag
I've been wondering how do other websites do their navigation links. What most beginners like me do is put the whole link inside the tag
<a href="www.example.com/news.html">News</a>
or something like this:
<a href="news.html">News</a>
But I've seen a lot of websites lately that does this:
<a href="/news.html">News</a>
and then the browser address bar display it like this
http://www.example.com/news/
First I want to know how do you call this method? and what are the advantages of doing this. and lastly, how does it actually work?.
I want to research about it but I don't know what to type on google. I did try a lot of keywords I could think of that relates to this but nothing comes close to what I'm looking for
Answer
Solution:
There's 4 basic link types:
self-link:
href=""
. This is a short-hand form of "link to yourself". You'll see it used for in-page anchors, such ashref="#top"
and the link.relative:
href="news.html"
. Clicking on this will try to load anews.html
page in the SAME directory as the page that the link is contained in, so if you're onhttp://example.com/foo/bar.html
, you'll be trying to loadhttp://example.com/foo/news.html
.local absolute:
href="/news.html"
. This will try to load anews.html
page from the document root of the site. If you're onhttp://example.com/foo/bar/html
, you'll be trying to loadhttp://example.com/news.html
. The leading/
is what makes this a local absolute instead of a relative path.full absolute:
href="http://example.com/news.html"
. A full-blown url, which can point to a completely different site if need be. It CAN be point to the exact same site you're on, but essentially it's a "go over there, no matter where over there is".Answer
Solution:
This has to do with HTML, not JavaScript. Your first snippet uses an absolute path. The second two use relative paths. For more information, read this: http://www.coffeecup.com/help/articles/absolute-vs-relative-pathslinks/
Answer
Solution:
The best practice (for me?) is the first one, you need to write all the URL for the most readable code..
The first and the 3rd link are the same if you are on the same domain name..
The 2nd is different, if you are on www.example.com/index.html you'll go to www.example.com/news.html.. But if you are on www.example.com/categoy/index.html you'll be redirected to www.example.com/categoy/news.html and not on root directory.
But I don't understand why you talk about /news/ directory ?
Answer
Solution:
Relative URL's will probably get you some results.
news.html
will navigate relative to your current location/news.html
will navigate relative to the root domain nameFor example if your current location is
http://example.com/sub/
:href="news.html"
will get you tohttp://example.com/sub/news.html
but
href="/news.html"
will get you tohttp://example.com/news.html
See also http://www.w3.org/TR/WD-html40-970917/htmlweb.html#h-5.1.2