3

I inherited an application that implements disabling F5 in a window popup.

<body onkeydown="disableF5();">

However if the user clicks below the body in the window and presses F5 the page will still refresh.

I moved the function call to

<html onkeydown="disableF5();">

and now F5 is disabled and everything is working as expected.

However this is not the best place to have code and I would prefer it if I could do something like below in my <script> section so I can add comments and perhaps move it to an external file.

$("html").attr("onkeydown", "disableF5();");

This snippet of jQuery does not work as expected however so I'm currently stuck at the moment.

Is there a way I can set the attributes of the <html> element?

Edit: I thought I would throw my disableF5() function in here.

function disableF5() {  
   if (window.event && window.event.keyCode == 116) { 
        window.event.cancelBubble = true;
        window.event.returnValue = false;
        window.event.keyCode = 0;
        window.status = "F5 is disabled on all popups";
        return false;
   }   
}
Biff MaGriff
  • 8,102
  • 9
  • 61
  • 98

3 Answers3

2
$('html').bind('keydown', function(){ disableF5(); });

See the documentation for $.bind()

Edit – Moderately verbose explanation:

HTML onstuff attributes are evaluated as the DOM is loaded. Adding them post-factum doesn't have any effect. Thus, proper JS event binding must be used.

vzwick
  • 11,008
  • 5
  • 43
  • 63
2

This works in latest Chrome and FireFox and seems cleaner than bind to me:

$(document.documentElement).keydown(disableF5);
fncomp
  • 6,040
  • 3
  • 33
  • 42
  • Have a +1 for bleeding edge … In a scenario where functions named `disableF5` are present, the exclusive use of Chrome/FF latest seems pretty unlikely though :D – vzwick Oct 25 '11 at 23:00
  • Yeah, I'm sad to say that all the users are, of course, on IE. – Biff MaGriff Oct 26 '11 at 14:37
1
$('html').bind('keydown', function() { disableF5(); }));
Clive
  • 36,918
  • 8
  • 87
  • 113