Link to home
Start Free TrialLog in
Avatar of Imaginx
Imaginx

asked on

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() {
	  	closeIt();
	});
	</script>

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.
Avatar of Mrunal
Mrunal
Flag of India image

Hi,
Try once with JavaScript "window.onclose" event instead of with jQuery.
Here is reference:

https://developer.mozilla.org/en/DOM/window.onclose

Also check this:
http://stackoverflow.com/questions/1631959/browser-window-close-event

Hope this helps you.
Avatar of Imaginx
Imaginx

ASKER

lol .. I actually read both of those pages in my google searches before posting the question here.

No such luck ..
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
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Imaginx

ASKER

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 !