Intercepting Clicks: Dangerous links

  1. Pop external links
  2. Intercepting Clicks
  3. Highlight the relevant link

Be careful how you use this knowledge. Designers love restricting their visitors, constraining their ability to leave the site and go somewhere else, restricting their ability to navigate except in predesigned paths. For the most part, you don’t need to open new windows for your visitors, because they can do that themselves if they want it.

Suppose, however, that there are some links we’ve categorized as dangerous. Maybe we’re writing about web viruses, and we’re giving some examples of pages that have been infected in the past. Or we’re writing about libel, and we’re giving some examples of pages that have libeled. For those links—and only those links—perhaps it makes sense to pop up a confirmation box reminding the visitor that they should be careful following this link.

The first step is to determine what makes a link dangerous. What criteria can we use to detect that we’ve categorized this link as dangerous but not some other link?

Most likely, if we’re categorizing links we’re also putting CSS classes on those links. For example, we might have a CSS class named “dangerous” that gets applied to dangerous links. JavaScript can check for that.

Go into the HTML for 1941.html and categorize three links as “dangerous”. Add “class="dangerous"” to the <a> tag for them. I recommend using the links in the link list (“<div id="links">”) towards the bottom of the page.

Then replace manageLinks with:

function manageLinks(event) {

var link = event.target;

//go up the family tree until we find the A tag

while (link && link.tagName != 'A') {

link = link.parentNode;

}

if (link) {

if (link.className == "dangerous") {

var confirmation = window.confirm(link.text + " might be dangerous. Are you sure you want to follow this link?");

return confirmation;

}

}

return true;

}

We can access the class attribute of an <a> tag using the className property. (The word “class” in JavaScript is reserved for other purposes.) The conditional “==” is the opposite of “!=”. It means “is equal to”. This conditional reads “if link.className is equal to ‘dangerous’ then…”.

One of the methods that windows have is the “confirm” method. It’s like an alert box, except that it provides both a “cancel” and an “OK” (or equivalent) button. If the visitor chooses “cancel”, window.confirm returns false. If the visitor chooses “OK”, window.confirm returns true. This matches what we return to tell the browser to follow or not follow the link, so we can just go ahead and return the result of window.confirm.

  1. Pop external links
  2. Intercepting Clicks
  3. Highlight the relevant link