1

I am trying to add an event to an element that fires when the page unloads. I would like to attatch the event to the element as I need to access private functions.

I decided to try and add an unload event to my element, and then call this function during the window.unload event, as the element is never passed an unload event normally.

Sadly I managed to create an infinite loop, I tried using the jQuery function 'one' in an attempt to stop the loop, and have also tried manually removing the unload even binding after the first call. Still no luck. I made a JsFiddle but decided not to link it because it will crash your browser, so here is the code.

<div id="myDiv"></div>
$('#myDiv').one('unload', function() { alert('Infinite loop incomming. Sorry :( '); });
$(window).unload(function() { $('#myDiv').unload(); });

Can anyone offer any advice or a better solution?

j08691
  • 204,283
  • 31
  • 260
  • 272
Random Developer
  • 175
  • 5
  • 17
  • What browser and OS are you using? I can't recreate an infinite loop with the code you've provided. – Anthony Grist Jul 03 '12 at 15:49
  • 1
    The alert you call just break the unload event – James Jul 03 '12 at 15:50
  • 1
    *I would like to attatch the event to the element as I need to access private functions.* what? – Esailija Jul 03 '12 at 15:52
  • I think I am approaching this the wrong way. Essentially I am trying to save the setting on a JqGrid as in this example - http://stackoverflow.com/questions/8545953/how-to-persist-current-row-in-jqgrid/8547852#8547852 . I would like to call the save function 'saveColumnState' when the window unloads, but I don't know how I can access it. – Random Developer Jul 03 '12 at 15:59

1 Answers1

1

I found what I was looking for in another question - Add jQuery function to specific elements.

Essentially I can use jQuery 'bind' and 'trigger' to add a custom event to the DOM element and call it later.

Example:

 <div id="myDiv"></div>

    $('#myDiv').bind('myUnloadFunction', function() { alert('No more loop :D'); });

    $(window).unload(function() { $('#myDiv').trigger('myUnloadFunction'); });
John
  • 93
  • 2
  • 8
Random Developer
  • 175
  • 5
  • 17