Body onunload event

Hi Guys!

I am trying to initiate fancybox popup on page unload (i.e. when the user closes the browser window). I managed to find the following script which does the opposite (launches when the page loads). How can I reverse this code so that it executes on body unload?

<script type="text/javascript">
	$(document).ready(function () {
        $.fancybox({
            'width': '40%',
            'height': '40%',
            'autoScale': true,
            'transitionIn': 'fade',
            'transitionOut': 'fade',
            'type': 'iframe',
            'href': 'http://www.example.com'
        });
});
</script>

</head>
<body id="home" onUnload="$('#aLink').trigger('click');">

Thanks in advance

The onbeforeunload event is the one that you’re after.

Demo: http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm

Okay so I tried this code, but it doesn’t seem to work:

<script type="text/javascript"> 
	$(window).onbeforeunload(function () {
        $.fancybox({
            'width': '40%',
            'height': '40%',
            'autoScale': true,
            'transitionIn': 'fade',
            'transitionOut': 'fade',
            'type': 'iframe',
            'href': 'http://www.exallgroup.com'
        });
});
</script>

Any idea whats wrong with it?

I don’t think that you can do that.

Please actually take the time to read the information about onbeforeunload on the onbeforeunload demo page.

JQuery doesn’t have processing for the beforeunload event as it is not a standard event. You would therefore need to use ordinary JavaScript calls to process that particular event in the browsers that support it.

This is demonstrated quite well at the following resource:
Using JQuery to Warn Users About Losing Data When Navigating Away from Form