Add confirmation dialog on rails app

2025-01-07 rails

Need to set the event listener like the below turbo:load. Since turbo framework skips entire page loading, DOMContentLoaded may not work properly.

// Force to add confirm dialog to danger(red) button
document.addEventListener("turbo:load", function() {
    for (const elm of document.getElementsByClassName("btn-danger")) {
        elm.addEventListener("click", function(event) {
            var confirmed = confirm("This action can not be undone. Are you sure?");
            if (!confirmed) {
              event.preventDefault();
            }
        });
        console.log("Added confirm dialog to:"+elm);
    }
});