I want this link to have a JavaScript dialog that asks the user “Are you sure? Y/N”.
<a href="delete.php?id=22">Link</a>
If the user clicks “Yes”, the link should load, if “No” nothing will happen.
I know how to do that in forms, using onclick
running a function that returns true
or false
. But how do I do this with an <a>
link?
In the most simple way, you can use the confirm()
function in an inline onclick
handler.
<a href="delete.php?id=22" onclick="return confirm('Are you sure?')">Link</a>
But normally you would like to separate your HTML and Javascript, so I suggest you don't use inline event handlers, but put a class on your link and add an event listener to it.
<a href="delete.php?id=22" class="confirmation">Link</a>
...
<script type="text/javascript">
var elems = document.getElementsByClassName('confirmation');
var confirmIt = function (e) {
if (!confirm('Are you sure?')) e.preventDefault();
};
for (var i = 0, l = elems.length; i < l; i++) {
elems[i].addEventListener('click', confirmIt, false);
}
</script>
This example will only work in modern browsers (for older IEs you can use attachEvent()
, returnValue
and provide an implementation for getElementsByClassName()
or use a library like jQuery that will help with cross-browser issues). You can read more about this advanced event handling method on MDN.
I'd like to stay far away from being considered a jQuery fanboy, but DOM manipulation and event handling are two areas where it helps the most with browser differences. Just for fun, here is how this would look with jQuery:
<a href="delete.php?id=22" class="confirmation">Link</a>
...
<!-- Include jQuery - see http://jquery.com -->
<script type="text/javascript">
$('.confirmation').on('click', function () {
return confirm('Are you sure?');
});
</script>