Skip to content
Advertisement

Javascript event not being set correctly in closure when called cross frame

I have the following code in the top frame of a two frame page:

JavaScript

This works on the original document load, but when I call this function from another frame (usually when only one frame reloads), the hook is set, but when the onkeydown function fires, it does not receive the appropriate arguments, instead evt == null.

Full Code follows:

KeyFrameTest.asp

JavaScript

KeyFrameTestTop.asp

JavaScript

KeyFrameTestBottom.asp

JavaScript

To recreate the issue, right click the bottom frame, click refresh, click “Reset Hooks”, and press keys.

Related Question: Handle keyPress Accross Frames in IE

I’ve also read an article on Javascript closures, but I’m not sure how it applies.

Sorry for the narrowness of question, but I really don’t know Javascript well enough to figure out the trick to this.

Advertisement

Answer

Here’s a solution that ditches the “old way” of handling events, and instead uses the more flexible and powerful “event listener” model. This allows the passing of event objects

Note that the attachEvent() method is IE only (which you stipulated as being ok in your previous post – but you’ll need to change this if you support something else)

JavaScript

When event listeners are registered this way, the proper event object is automatically passed as an argument to the handler function.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement