A pattern that's started to show up a lot in one of the web apps I'm working are links that used to just be a regular a-tag link now need a popup box asking "are you sure?" before the link will go. (If the user hits cancel, nothing happens.)
We've got a solution that works, but somehow we're a web app shop without a Javascript expert, so I'm left with this crawling feeling like there's a better way to get the job done.
So, JS experts, what's the most standards-compliant, cross-browser way to get this done?
(For the record, this is already a site that requires JS, so no need to have a "non-JS" version. But, it does need to work in any and all reasonably modern browsers.)
(Also, for bonus points it would be nice if people with JS turned off didn't have the links work, rather than bypassing the confirm box.)
JavaScript | Replace() Method The replace() method in JavaScript is used to replace the current page with another page. The Replace Method replaces the URL of the current window by the URL mention in the Replace method.
You should use '&' instead found in php-style links (i.e. < a href="index.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With