Javascript/jQuery - confirmation dialog on href-link

By Inline event handler

In the most simple way, we can use the confirm() function in an inline onclick handler.

1
<a href="https://www.blogger.com/delete.php?id=22222" onclick="return confirm('Are you sure?')">Link</a>
Using Advanced event handling

But normally we would like to separate HTML and Javascript, so we don't use inline event handlers, but put a class on our link and add an event listener to it.
1
<a class="confirmation" href="https://www.blogger.com/delete.php?id=2222">Link</a>
1
2
3
4
5
6
7
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);
}
By jQuery

Just for fun, here is how this would look with jQuery
1
<a class="confirmation" href="https://www.blogger.com/delete.php?id=22222">Link</a>
1
2
3
$('.confirmation').on('click', function () {
    return confirm('Are you sure want to delete this item?');
});

No comments:

Post a Comment