One final step before we leave link-munging behind. While popping up the alert box, it would be nice to highlight the link they just clicked on. JavaScript has full access to the styles of HTML elements. We can set the background color of the link tag to, for example, bright red.
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 normalBackground = link.style.backgroundColor;
link.style.backgroundColor = "red";
var confirmation = window.confirm(link.text + " might be dangerous. Are you sure you want to follow it?");
link.style.backgroundColor = normalBackground;
return confirmation;
}
}
return true;
}
All of the styles of an element are stored in the style property on that element; the style property is itself an object with properties of its own. Those properties are CSS styles. The dashes are removed, and the succeeding words capitalized. The style “background-color” becomes the property “backgroundColor”.
In this example, we first store the existing background color, set the background color to red, handle the confirmation, and then reset the background color to whatever it was before.
Highlight the relevant link: Odd change
One of the things about JavaScript is that how it works often changes, sometimes in response to the annoying things web spammers do, and sometimes because the behavior is simply undefined.
Despite the sample image, changing the background color before displaying an alert window doesn’t work in Safari: Safari’s behavior has changed since I wrote that part of this tutorial. Safari waits until the script ends to update the style change, at which point we’ve changed it back to the original. As I write this in March 2012, this code does work as expected in Chrome and Firefox.
This is one of those cases where you have to decide if the inconsistency matters. Is the red background color critical, or is it just something to make it easier for the visitor if the visitor happens to be using a browser that supports it?