Created
May 28, 2020 02:46
-
-
Save harish81/6f82922b5f93b505a0a1ae080ce0fbb6 to your computer and use it in GitHub Desktop.
Promise Based Bootstrap Modal As Confirmation Box or Alert.
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 bsPopup(title = 'Alert', msg = 'Are you sure?') { | |
return new Promise((resolve, reject) => { | |
const autoId = 'modal' + new Date().getTime(); | |
const modal = ` | |
<div class="modal fade" id="${autoId}" tabindex="-1"> | |
<div class="modal-dialog modal-dialog-centered" role="document"> | |
<div class="modal-content"> | |
<div class="modal-header"> | |
<h5 class="modal-title"><i class="fa fa-exclamation-triangle mr-1"></i> ${title}</h5> | |
<button type="button" class="close" data-dismiss="modal" aria-label="Close"> | |
<span aria-hidden="true">×</span> | |
</button> | |
</div> | |
<div class="modal-body">${msg}</div> | |
<div class="modal-footer"> | |
<button type="button" class="btn btn-secondary modal-cancel" data-dismiss="modal">CANCEL</button> | |
<button type="button" class="btn btn-primary modal-ok">OK</button> | |
</div> | |
</div> | |
</div> | |
</div>`; | |
$('body').append(modal); | |
let modalElem = $("#" + autoId); | |
modalElem.modal('show'); | |
modalElem.on('hidden.bs.modal').click((e) => { | |
modalElem.remove(); | |
$('.modal-backdrop').remove(); | |
$('body').removeClass("modal-open"); | |
reject(false); | |
}); | |
modalElem.find(".modal-ok").click(() => { | |
modalElem.remove(); | |
$('.modal-backdrop').remove(); | |
$('body').removeClass("modal-open"); | |
resolve(true); | |
}); | |
}); | |
} | |
function confirmPrompt(event) { | |
if(!event.isTrusted) return true; | |
event.preventDefault(); | |
bsPopup().then(rs=>{ | |
if(rs) { | |
event.target[event.type](); | |
} | |
}); | |
return false; | |
} |
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
<!--How to use--> | |
<a onclick="confirmPrompt(event)" href="google.com">test</a> | |
<form action="" onsubmit="return confirmPrompt(event)"> | |
<button type="submit">submit</button> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Full Example: https://jsfiddle.net/vwhpcuoe/