• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 467
  • Last Modified:

jQuery on Window Close

I need a jquery solution that will trigger a function on a windowClose event.

I currently have:

	<script type='text/javascript'>
	function closeIt(){
	     alert("Page has Closed");
		// logOutUser();
	$(window).unload(function() {

Open in new window

The problem with .unload() is that it's trigger anytime the DOM is unloaded. So every time you click any link on the page, the DOM is unloaded & then reloaded with the new page content. This triggers the closeIt() function.

I need to only trigger the function when the window is closed, or if someone is to leave the domain - so I can make an ajax call & record the log out in the db.

TIA Experts.
  • 2
  • 2
1 Solution
Try once with JavaScript "window.onclose" event instead of with jQuery.
Here is reference:


Also check this:

Hope this helps you.
ImaginxAuthor Commented:
lol .. I actually read both of those pages in my google searches before posting the question here.

No such luck ..
Michel PlungjanIT ExpertCommented:
This is such a FAQ.
You need onbeforeunload and you need to set a flag onload and clear it when internal links are clicked - test it onbeforeunload and log them out
In addition your server needs to handle the fact that some users will not trigger your script
Michel PlungjanIT ExpertCommented:
Here is an old but still valid post

ImaginxAuthor Commented:
mplungjan, that's a great link.

apparently theres no perfect solution for what im trying to achieve, but theres enough information in that post for me a come up what a different viable solution.

Thanks !
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Easily Design & Build Your Next Website

Squarespace’s all-in-one platform gives you everything you need to express yourself creatively online, whether it is with a domain, website, or online store. Get started with your free trial today, and when ready, take 10% off your first purchase with offer code 'EXPERTS'.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now