Last active
August 3, 2021 18:56
-
-
Save tomazy/3c946214ae477b27230c00801be70828 to your computer and use it in GitHub Desktop.
Overwrite `window.confirm` with a custom modal dialog (Rails + jquery-ujs + data-confirm attribute)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { [9/55928] | |
'use strict'; | |
function showConfirmBox(message, cb) { | |
var $modal = $('.js-modal-confirm'); | |
var $btnYes = $modal.find('.js-yes') | |
var $btnCancel = $modal.find('.js-cancel') | |
$modal.find('.js-message').text(message) | |
$modal.show(); | |
$btnYes.one('click', function(){ | |
$modal.hide(); | |
$btnCancel.off('click'); | |
cb(true); | |
}); | |
$btnCancel.one('click', function(){ | |
$modal.hide(); | |
$btnAdd.off('click'); | |
cb(false); | |
}); | |
} | |
$(document).on('confirm', '[data-confirm]', function(e){ | |
var $el = $(this); | |
showConfirmBox($el.data('confirm'), function(confirmed){ | |
if (confirmed) { | |
// simulate a click on the element but clean the data-confirm attribute first | |
// so that we don't get into a loop | |
$el.data('confirm', null); | |
$el.trigger('click.rails'); | |
} | |
}); | |
// prevent the default behaviour of showing the standard window.confirm dialog | |
return false; | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment