views:

103

answers:

1

I add an event to a frame using the inline syntax:

<FRAME SRC="s.htm" NAME="WINCONTENT" onload="alert( this )"> 

This works (=the event fires whenever a new URL is loaded), except that I'd much rather register events using addEventListener/attachEvent.

Now -- in the onload="alert( this ) example this is set to HTMLFrameElement. How do I access HTMLFrameElement from inside JavaScript? (I need to specify it as an argument for addEventListener/attachEvent)

Note that parent.WINCONTENT and the like point to a Window object whereas what I need is HTMLFrameElement. I have googled quite a bit but apparently frames have been unfashionable for a while.

Complete listings below:

index.htm

<HTML>
<HEAD>
<TITLE>WINMAIN</TITLE>
</HEAD>
<FRAMESET COLS=255,*>
<FRAME SRC="frm_navi.htm"  NAME="WINNAVI">
<FRAME SRC="s.htm" NAME="WINCONTENT" ID="WINCONTENT">
</FRAMESET>
</HTML>

frm_navi.htm

<HTML>
<HEAD>
<TITLE>Navigation Pane</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript" SRC="dom.js"></SCRIPT>
</BODY>
</HTML>

s.htm

<HTML>
<HEAD>
<TITLE>CONTENTS</TITLE>
</HEAD>
<BODY>
    <P><A HREF="r.htm">r.htm</A></P>
    <P><DIV ID="test">Click me, the event handler was registered in JavaScript</DIV></P>
</BODY>
</HTML>

r.htm

<HTML>
<HEAD>
<TITLE>CONTENTS</TITLE>
</HEAD>
<BODY>
    <P>This file s.htm</P>
</BODY>
</HTML>

dom.js

function register_event ( _target, _ename, _func ) {
    if( ! _target ) {
        return false;
    }

    // Required for accessing <this> inside the event handling function.
    _target[_func] = _func;
    if ( _target.addEventListener ) {
        _target.addEventListener( 
            _ename, 
            function(e) { _target[_func](e);}, 
                false
            );
    }
    else if ( _target.attachEvent ) {
        _target.attachEvent( 
            "on" + _ename, 
            function(e) { _target[_func](e);}
        );
    }
    else {
        return false;
    }

    return true;
};

function handle_event ( ) {
    alert( "Event handler registered in JS." );
};

register_event( parent.WINCONTENT.document.getElementById( "test" ) , "click", handle_event );
register_event( "_what_do_i_enter_here_ ???", "load", handle_event );
A: 

Can't you just assign an ID to your frame element and use document.getElementsById (from within the parent document)?

Marcel Korpel
Can I get a frame using getElementByID?I have added listings (verified in FF)The missing bit of the puzzle is in the last line: "_what_do_i_enter_here_ ???"
WHOA, the following works register_event( parent.document.getElementById( "WINCONTENT" ) , "load", handle_event );K.