Unobtrusive Javascript
The best practice is to add event handler methods to the links.
The confirm() function produces the dialog box you described, and returns true or false depending on the user's choice.
Event handler methods on links have a special behavior, which is that they kill the link action if they return false.
var link = document.getElementById('confirmToFollow');
link.onclick = function () {
return confirm("Are you sure?");
};
If you want the link to require javascript, the HTML must be edited. Remove the href:
<a href="#" id="confirmToFollow"...
You can explicitly set the link destination in the event handler:
var link = document.getElementById('confirmToFollow');
link.onclick = function () {
if( confirm("Are you sure?") ) {
window.location = "http://www.stackoverflow.com/";
}
return false;
};
If you want the same method called on multiple links, you can acquire a nodeList of the links you want, and apply the method to each as you loop through the nodeList:
var allLinks = document.getElementsByTagName('a');
for (var i=0; i < allLinks.length; i++) {
allLinks[i].onclick = function () {
return confirm("Are you sure?");
};
}
There are further permutations of the same idea here, such as using a classname to determine which links will listen for the method, and to pass a unique location into each based on some other criteria. They are six of one, half dozen of another.
Alternative Approaches (not encouraged practices):
One discouraged practice is to attach a method via an onclick attribute:
<a href="mypage.html" onclick="...
Another discouraged practice is to set the href attribute to a function call:
<a href="javascript: confirmLink() ...
Note that these discouraged practices are all working solutions.