JavaScript event handler scope and this
<p>If I want to dynamically add an event handler to an HTML element, and not discard or break any existing event handler.</p>

<p>The code below will not do that because if the existing handler registered for an event on the element referred to 'this', my chaining of handlers would break that. I'd actually like to be able to use 'this' in the new handler too if possible, but I could always get around that I guess.</p>

<pre><code>&lt;script type="text/javascript"&gt;

    function oldHandler()
    {
         alert("old handler; this.value=" +this.value);
    }

&lt;/script&gt;

&lt;form name="test1" id="test1"&gt;

    &lt;fieldset&gt;
        &lt;legend&gt;My Test&lt;/legend&gt;
        &lt;ol&gt;
            &lt;p&gt;
            &lt;li&gt;
                &lt;label for="tf1"&gt;Test Field 1&lt;/label&gt;
                &lt;input id="tf1" onchange="existingHandler();" name="tf1"/&gt;
            &lt;/li&gt;
        &lt;/ol&gt;
    &lt;/fieldset&gt;

&lt;/form&gt;

&lt;script type="text/javascript"&gt;

    function myAddHandler(element, event, newHandler)
    {
        var existingHandler = element[event];
        element[event] = function() {
                            newHandler();
                            existingHandler();
                         }
    }

    function myOnChangeHandler()
    {
        alert("new handler; this.value=" +this.value);
    }

    myAddHandler(document.getElementById('tf1'), "onchange", myOnChangeHandler);

&lt;/script&gt;
</code></pre>

<p>Thanks.</p>
