Reputation: 1523
I'm trying to use semantic-ui to block transfer away from a page with a modal dialog, however, e.preventDefault() appears not to work:
<!DOCTYPE html>
<html>
<head>
<title>Modal Block HREF</title>
<link rel="stylesheet" type="text/css" href="node_modules/semantic-ui/dist/semantic.min.css">
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/semantic-ui/dist/semantic.min.js"></script>
</head>
<body>
<a class="dirty" href="http://www.microsoft.com">Microsoft</a>
<a class="dirty" href="http://www.google.com">Google</a>
<div id="confirmmodal" class="ui small modal">
<div class="header">FIRST</div>
<div class="content">
<div class="left">
The first of many interesting things
</div>
</div>
<div class="actions">
<div class="ui black deny button">
Cancel
</div>
<div class="ui positive button">
OK
</div>
</div>
</div>
<div id="savemodal" class="ui small modal">
<div class="header">SECOND</div>
<div class="content">
<div class="left">
The second of many interesting things
</div>
</div>
<div class="actions">
<div class="ui black deny button">
Cancel
</div>
<div class="ui positive button">
OK
</div>
</div>
</div>
<script type="text/javascript">
$('.dirty').on('click', function(e, t) {
// This works...
//if (confirm('Are you sure')) {
// console.log("allow transfer");
//}
//else {
// console.log("block transfer");
// e.preventDefault();
//}
// This does NOT work
$('#confirmmodal')
.modal({
onApprove: function () {
console.log("allow transfer");
},
onDeny: function () {
console.log("prevent transfer");
e.preventDefault();
}
})
.modal('show');
});
</script>
</body>
</html>
What seems to happen is the link is responded to immediately before the dialog even appears, and even if I click on Cancel quickly, it makes no difference.
Upvotes: 0
Views: 1003
Reputation: 929
You need to prevent the first click from submitting the page. Use the below
<script type="text/javascript">
$('.dirty').on('click', function(e, t) {
e.preventDefault();
var href = $(this).attr("href");
$('#confirmmodal') .modal({
onApprove: function () {
console.log("allow transfer");
window.location = href;
},
onDeny: function () {
console.log("prevent transfer");
}
}) .modal('show');
});
</script>
Upvotes: 1