@@ -26,19 +26,28 @@ document.addEventListener("DOMContentLoaded", () => {
2626 } ) ;
2727 } ) ;
2828
29- const form = document . querySelector ( ' .edit_story' ) ;
30- const backButton = document . getElementById ( ' back' ) ;
31- const logo = document . getElementById ( ' logo' ) ;
29+ const form = document . querySelector ( " .edit_story" ) ;
30+ const backButton = document . getElementById ( " back" ) ;
31+ const logo = document . getElementById ( " logo" ) ;
3232 let isDirty = false ;
3333
34- // Mark the form as dirty when any input changes
35- form . addEventListener ( 'input' , function ( ) {
36- isDirty = true ;
37- } ) ;
34+ if ( form ) {
35+ // Mark the form as dirty when any input changes
36+ form . addEventListener ( "input" , function ( ) {
37+ isDirty = true ;
38+ addBeforeUnloadEventListener ( isDirty ) ;
39+ } ) ;
40+
41+ // Reset isDirty on form submission
42+ form . addEventListener ( "submit" , function ( ) {
43+ isDirty = false ;
44+ addBeforeUnloadEventListener ( isDirty ) ;
45+ } ) ;
46+ }
3847
3948 // Attach a click event to the custom back button
4049 [ backButton , logo ] . forEach ( element => {
41- element . addEventListener ( ' click' , function ( event ) {
50+ element . addEventListener ( " click" , function ( event ) {
4251 if ( isDirty ) {
4352 const confirmLeave = confirm ( "You have unsaved changes. Are you sure you want to go back?" ) ;
4453 if ( ! confirmLeave ) {
@@ -47,22 +56,20 @@ document.addEventListener("DOMContentLoaded", () => {
4756 } else {
4857 // Optionally, reset isDirty if leaving
4958 isDirty = false ;
59+ addBeforeUnloadEventListener ( isDirty )
5060 }
5161 }
5262 } )
5363 } ) ;
64+ } ) ;
5465
55- // Reset isDirty on form submission
56- form . addEventListener ( 'submit' , function ( ) {
57- isDirty = false ;
58- } ) ;
59-
66+ function addBeforeUnloadEventListener ( isDirty ) {
6067 if ( isDirty ) {
6168 window . addEventListener ( "beforeunload" , warnUserifUnsavedEdits ) ;
6269 } else {
6370 window . removeEventListener ( "beforeunload" , warnUserifUnsavedEdits ) ;
6471 }
65- } ) ;
72+ }
6673
6774function warnUserifUnsavedEdits ( event ) {
6875 event . preventDefault ( ) ;
0 commit comments