PDF Links Labeling

Garret Dimon wrote nice post about why .PDF links should be labeled. While there’s no problem making these labels when starting from scratch or re-designing web site, it’s a pain in the a** to add class="pdfLink" to existing (large) sites. Here’s JavaScript to the rescue.

If you have read my post about adding target=”_blank” to external links, you are half way there. The script is basically the same, but the conditions are changed. Instead of applying target attribute to all external links, the script applies this attribute to all URLs that have a string ‘.pdf’ in it or as you will see later, to any custom file extension (i know some of you will disagree with opening links in new window, but that’s not today’s topic).

The script also adds class="pdfLink" to all links that match the condition. Same could be applied to .DOC files or .ZIP files.

function fileLinks() {
    var fileLink;
    if (document.getElementsByTagName('a')) {
        for (var i = 0; (fileLink = document.getElementsByTagName('a')[i]); i++) {
            if (fileLink.href.indexOf('.pdf') != -1) {
                fileLink.setAttribute('target', '_blank');
                fileLink.className = 'pdfLink';
            }
            if (fileLink.href.indexOf('.doc') != -1) {
                fileLink.setAttribute('target', '_blank');
                fileLink.className = 'docLink';
            }
            if (fileLink.href.indexOf('.zip') != -1) {
                fileLink.setAttribute('target', '_blank');
                fileLink.className = 'zipLink';
            }
        }
    }
}
window.onload = function() {
    fileLinks();
}

preview of icons Now that we have classes pdfLink, docLink and zipLink, we can use CSS to style those links, for example add a corresponding icons. See following example:

.pdfLink { padding-right: 19px; background: url(pdf.gif) no-repeat 100% .5em; }
.docLink { padding-right: 19px; background: url(doc.gif) no-repeat 100% .5em; }
.zipLink { padding-right: 17px; background: url(zip.gif) no-repeat 100% .5em; }

I suggest you use small and unobtrusive, but noticeable icons, otherwise they will take too much attention. Here is full working example. The script is not bullet-proof to URL junk produced by CMS, for example ?download=2387423&sid=8568347563. Links should point to files with the right extensions.

Marko Dugonjić is a designer specialized in user experience design, web typography and web standards. He runs a nanoscale user interface studio Creative Nights and organizes FFWD.PRO, a micro-conference and workshops for web professionals.

Interested in more content like this?