Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Unobtrusive Javascript</strong></p> <p>The best practice is to add event handler methods to the links.</p> <p>The <em>confirm()</em> function produces the dialog box you described, and returns true or false depending on the user's choice.</p> <p>Event handler methods on links have a special behavior, which is that they kill the link action if they return false.</p> <pre><code>var link = document.getElementById('confirmToFollow'); link.onclick = function () { return confirm("Are you sure?"); }; </code></pre> <p>If you want the link to <strong>require javascript</strong>, the HTML must be edited. Remove the href:</p> <pre><code>&lt;a href="#" id="confirmToFollow"... </code></pre> <p>You can explicitly set the link destination in the event handler:</p> <pre><code>var link = document.getElementById('confirmToFollow'); link.onclick = function () { if( confirm("Are you sure?") ) { window.location = "http://www.stackoverflow.com/"; } return false; }; </code></pre> <p>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:</p> <pre><code>var allLinks = document.getElementsByTagName('a'); for (var i=0; i &lt; allLinks.length; i++) { allLinks[i].onclick = function () { return confirm("Are you sure?"); }; } </code></pre> <p>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.</p> <p><strong>Alternative Approaches (not encouraged practices):</strong></p> <p>One <strong>discouraged practice</strong> is to attach a method via an <strong>onclick attribute</strong>:</p> <pre><code>&lt;a href="mypage.html" onclick="... </code></pre> <p>Another <strong>discouraged practice</strong> is to set the <strong>href attribute</strong> to a function call:</p> <pre><code>&lt;a href="javascript: confirmLink() ... </code></pre> <p>Note that these discouraged practices are all working solutions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload