May 23, 2012

How can I add event handler to a html object?

Each HTML object has many event handler (onclick, onkeyup, onfocus, etc.) Sometimes we need to execute own routines when an event occurs. How can we assign our function to the event handler?

1. The simplest case is that when we can directly assign our function to the handler of an element:
<script type="text/javascript">
  document.body.onclick = function() { alert('Hello World'); };
</script>
2. But when our function is bigger and moreover, we must assign it to more event hadlers the solution above is not effective. Then we must define our function normally and assign its pointer to the event hadlers.
In this case I use MyAddEvent() function defined below. With this function I can attach my special event handler (attribute: pFunctionPointer) to any DHTML element (attribute: oElement).
<script type="text/javascript">

  function MyAddEvent(oElement, sEventName, pFunctionPointer) {
    sEventName = sEventName.replace(/^on/,'');
    if(document.all) oElement.attachEvent('on'+sEventName, pFunctionPointer);
    else oElement.addEventListener(sEventName, pFunctionPointer, true );
  }

  function MyFunction(oEvent) {
    var oInput = document.getElementById('myinput');
    oInput.value += '=';
  }

  function MyOnLoad() {
    var oInput = document.getElementById('myinput');
    MyAddEvent(oInput, 'keydown', MyFunction);
    MyAddEvent(oInput, 'blur', MyFunction);
  }

</script>

No comments:

Post a Comment