Thursday, January 17, 2008

Print links in printable version using javascript

With screen media, one can easily link pages on the web(Eg:Click here to visit Google . But when a user 'prints' the page, all your links will probably be lost or atleast won't print as you want them. To avoid this, it would be nice if we could somehow bundle the links with the printed matter. That is what I recently wanted for my website and I found that javascript could easily help me.

To see what I mean, see the below screenshot. It is a printable version of one the pages of my website.



The logic is to extract hyperlinks from the body of print matter and list them seperately near the footer. To see a live example, click the "Print this page" link in bottom-right of this page.

You would be shown as printer friendly format of that page with outbound links from the body-matter extracted and put in a seperate area.

So how do we do that?Its simple 3 steps!
  1. Use javascript function to getElementsByTagName. Since we need to get elements with "a" (anchor) tag, we collect all hyperlinks on by document.getElementsByTagName('a'). This will return an array of all hyperlinks in the matter. Lets call this array as links.
  2. Calculate size of the above obtained array using links.length function.
  3. Now lets run a loop that will execute it as many times as the no. of hyperlinks. In every loop, we perform three actions: 1. Get HREF attribute of a hyperlink. 2. Get TITLE attribute of the hyperlink and 3. We print the hyperlink's title and HREF attribute.
So, our code would look like below
var links=document.getElementsByTagName("a"); // returns an array of all hyperlinks
var no=links.length;// Calculates no of hyperlinks
if(no>0) // execute further action only if atleast 1 hyperlink is found in the matter
{
document.write("Important links from this page have been given below. Please visit them:
")
for(i=0;iWe start the loop
{
href=document.links[i].href;//We obtained the HREF attribute of a hyperlink
var title=document.links[i].title;//We obtained the TITLE attribute of the same hyperlink
document.write(""+title+":
=>"+href+"
");} //Now we write the link
}
else
{
false;// return false if o hyperlink is found in the matter
}
To get this method working, you need to have the TITLE attribut for every link in your matter. If you don't have, then you may decide to skip the title and only print the HREF attribute.

No comments: