I’m attaching a htmx:confirm
event listener to the body so as to override the default browser confirm UI with sweetalert2 library as shown in this example. However I’m running into unnecessary prompts every time Htmx makes an ajax call. Below is my Html.
<!DOCTYPE html>
<html>
<head>
<title>htmx test</title>
</head>
<body>
<h1>TODOs</h1>
<div id="content" hx-get="https://jsonplaceholder.typicode.com/todos/1" hx-trigger="load">
<p>...loading</p>
</div>
<br/>
<button id="btn-change" hx-get="https://jsonplaceholder.typicode.com/todos/2" hx-target="#content">Change TODO</button>
<button id="btn-change-w-confirm" hx-get="https://jsonplaceholder.typicode.com/todos/3" hx-confirm="Are you sure you want to change todo?" hx-target="#content">Change TODO w/Confirm</button>
<script src="https://unpkg.com/[email protected]" integrity="sha384-ujb1lZYygJmzgSwoxRggbCHcjc0rB2XoQrxeTUQyRjrOnlCoYta87iKBWq3EsdM2" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.body.addEventListener('htmx:confirm', function(e) {
console.log('htmx:confirm', e.detail);
e.preventDefault();
Swal.fire({
title: e.detail.question,
showCancelButton: true,
icon: "warning",
}).then(function(result) {
if(result.isConfirmed) e.detail.issueRequest(true);
});
});
</script>
</body>
</html>
The expected behavior is only #btn-change-w-confirm
should be displaying the confirm message as it has hx-confirm
attribute. However the confirm message is displayed by all ajax calls including when the page loads and the other button without the confirm.
How do I restrict htmx:confirm event to those elements with hx-confirm attribute?