Biff MaGriff
Biff MaGriff

Reputation: 8231

How can I rewrite onkeydown on the html element?

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;
   }   
}

Upvotes: 3

Views: 1567

Answers (3)

fncomp
fncomp

Reputation: 6188

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

$(document.documentElement).keydown(disableF5);

Upvotes: 2

vzwick
vzwick

Reputation: 11044

$('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.

Upvotes: 2

Clive
Clive

Reputation: 36957

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

Upvotes: 1

Related Questions