0

I have this process setup to ask if the user wishes to leave the chat room. If yes then the unload is processed and it writes a message in the room that the user left the chat room and reduces the chatroom occupancy by 1.

That part works fine...

However if the user selects to stay (and clicks 'stay' on the popup) then it stays on the page which is fine.. However the next time the user decides to leave the beforeunload is not executed second time and he receives no question on the page.

So how do i reset the beforeunload if they stay on the page so it can be executed again?

Here is my code:

   /* ask them the question about leaving */

   $(window).one("beforeunload", function () {
       return 'Do you want to leave the chat room?';
   });

   /* they chose to leave */

  $(window).one("unload", function () {    

     /* post left room text msg */        
     /* adjust room count */

 });
James Westgate
  • 11,306
  • 8
  • 61
  • 68
dave
  • 1

1 Answers1

1

You are attaching event handlers using .one - this means they will only be executed once as per your description. Try changing them to .on as follows:

   //Ask them the question about leaving
   $(window).on('beforeunload', function () {
       return 'Do you want to leave the chat room?';
   });

   //They chose to leave    
   $(window).on('unload', function () {    
      /* post left room text msg */        
      /* adjust room count */    
   });
James Westgate
  • 11,306
  • 8
  • 61
  • 68
  • 1
    Thank you very much for the lesson, i did not realize that... :) you are very kind. – dave Dec 20 '17 at 11:58
  • Just a quick note after testing this out... both [on] and [bind] work on chrome perfectly but neither one works on firefox for some reason. I thought that was worth mentioning. – dave Dec 20 '17 at 12:06
  • `.bind` has been deprecated for a long time in jQuery. Unfortunately those events don't work consistently across browsers - see https://stackoverflow.com/questions/14645011/window-onbeforeunload-and-window-onunload-is-not-working-in-firefox-safari-o – James Westgate Dec 20 '17 at 12:09
  • Yes i just wanted to see if [bind] might still work in FF... thanks for the link you have been a great help. :) – dave Dec 20 '17 at 12:17