Free version available
Magnifying Glass

The PocketSmith Blog

Syndicated Posts

FaceBook

Twitter

Cleaning up nasty body onload events using Prototype

Thursday, April 2nd, 2009 by James

I have another solid geek post on load balancing in Rails brewing, but for the moment I’ll quickly document a change that I have just made.

PocketSmith logs people out after a set period of time – currently 30 minutes. When this occurs, an overlay pops up over the screen notifying the user that they have been logged out. In order to get this out the door as quickly as possible a couple of months back, we hastily placed the code that performed this business in the body tag, using crusty onloads / onmousedown events, ala:

<body onkeydown="resetTimeout();" onmousedown='resetTimeout();' onload="timeoutObject=setTimeout('notifyLogout()',timePeriod);">

Now we’ve just switched over to use the (relatively less naughty, but still should be more unobtrusive) Prototype Event.observe functions to perform exactly the same thing. The below code is in a script tag at the end of each page.

<script type="text/javascript">
Event.observe(window, 'load', function() {
    timeoutObject = setTimeout('notifyLogout();',timePeriod);
    Event.observe(document, "keypress", function() {
        resetTimeout();
    });
    Event.observe(document, "click", function(){
        resetTimeout();
    });
});
</script>

This means that the onload has been replaced with Event.observe(window, ‘load’, function() {your_functions_here}, and the onkeydown / onmousedown has been replaced with the Event.observe(document, “keypress”, function() {your_functions_here} and Event.observe(document, “click”, function(){your_functions_here}.

So now, we have nice and clean <body> tags again. Hoorah!

Tags:

Leave a Reply