Una dintre funcționalitățile care cred că ar trebui să fie prezente oriunde sunt folosite formulare este confirmarea când vrei să închizi pagina dar ai lucruri ne…salvate. Pe desktop este inadmisibil să închizi o aplicație fără să te întrebe dacă vrei să salvezi, de ce e diferit pe web?
În fine, treaba asta se poate implementa ușor în WordPress, așa:
// wp-content/themes/tema-mea/assets/javascript/prevent-comment-leave-alert.js
(function () {
const comment = document.querySelector('#comment');
const commentForm = document.querySelector('#commentform');
if (!commentForm || !comment) {
return;
}
const bindAlert = () => comment.value.length > 10 ? true : null;
const unbindAlert = () => { window.onbeforeunload = null; };
window.onbeforeunload = bindAlert;
commentForm.addEventListener('submit', unbindAlert, false);
})();
Folosim acest script așa:
// wp-content/themes/tema-mea/functions.php SAU comments-template.php
add_action('comment_form_after', function () {
wp_enqueue_script('prevent-comment-leave-alert', get_stylesheet_directory_uri() . '/assets/javascript/prevent-comment-leave-alert.js', [], '1.0.0', true);
})