0

I've got a page with a bunch of text boxes where users enter hours for each day. The text boxes have an event handler that runs to save the data when it is changed. Using jQuery change(). The problem is that when some users get to the last input they enter the data then close the page or navigate away. So it never loses focus and the change event handler isn't called. Is there a way, short of keyup/keydown, to catch that final change before the page unloads?

I know I could always switch it to a traditional form with a submit button, but they were hoping to avoid that.

Thanks in advance.

1 Answer 1

0

MDN has a good example of doing this.

document.onvisibilitychange = () => {
  if (document.visibilityState === "hidden") {
    navigator.sendBeacon("/log", analyticsData);
  }
};

In your case, this would do two things:

  1. It triggers any time the tab is "hidden" (so if it's closed, or even if someone switches to another tab)
  2. It sends some data to a server

Be aware that sendBeacon() only POSTs data, and you don't get a response back. The benefit is that it is an async call that can outlast the life of the page, so even though the page is being torn down, the call still (hopefully) succeeds. There is also a keepalive param you can use with a normal XHR that will accomplish the same thing, although Firefox doesn't support it yet.

Not the answer you're looking for? Browse other questions tagged or ask your own question.