faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

38 of 49 people (78%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

How can I add/combine two event handlers?

Feb 15th, 2000 05:41
Martin Honnen,


You might want to add some event handler for an event to an element to 
which there is already an event handler attached. That is possible by 
storing the old event handler somewhere and then writing a new function 
which calls the old event handler.
For example suppose you have a document with buttons with onclick 
handlers
  <INPUT TYPE="button" NAME="aButton" VALUE="praise God"
         ONCLICK="alert('Hail the Kibo');"
  >
and you want add script that disables the event handler temporarily then 
you store the old event handler
  var button = document.formName.aButton;
  button.oldOnClick = button.onclick;
and write your new click handler which calls the oldOnClick when 
necessary
  function disabledButton (evt) {
    if (this.disabled)
      return false;
    else
      if (this.oldOnClick)
        this.oldOnClick(evt);
  }
  button.onclick = disabledButton;
Now you can set
  button.disabled = false;
to disable the button and
  button.disabled = true;
to enable it. Complete example:
         
<HTML>
<HEAD>
<STYLE>
</STYLE>
<SCRIPT>
  function disabledButton (evt) {
    if (this.disabled)
      return false;
    else
      if (this.oldOnClick)
        this.oldOnClick(evt);
  }
  function setUpButtonDisabling () {
    for (var f = 0; f < document.forms.length; f++)
      for (var e = 0; e < document.forms[f].elements.length; e++)
        if (document.forms[f].elements[e].type == 'button') {
          document.forms[f].elements[e].oldOnClick = 
            document.forms[f].elements[e].onclick;
          document.forms[f].elements[e].onclick = disabledButton;
        }
  }
</SCRIPT>
</HEAD>
<BODY ONLOAD="setUpButtonDisabling();">
<FORM NAME="formName">
  <INPUT TYPE="button" NAME="aButton" VALUE="praise God"
         ONCLICK="alert('Hail the Kibo');"
  >
  <INPUT TYPE="BUTTON" VALUE="toggle disabled"
         ONCLICK="this.form.aButton.disabled = 
!this.form.aButton.disabled;"
  >
</FORM>
<FORM NAME="aForm">
  <INPUT TYPE="button" NAME="aButton" VALUE="show date"
         ONCLICK="alert(new Date());"
  >
  <INPUT TYPE="BUTTON" VALUE="toggle disabled"
         ONCLICK="this.form.aButton.disabled = 
!this.form.aButton.disabled;"
  >

</FORM>
</BODY>
</HTML>