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.

Link
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.
Link
    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
Link
    $('.confirmation').on('click', function () {
        return confirm('Are you sure want to delete this item?');
    });

No comments:

Post a Comment