javaScript HTMLdom events

the event is some notable action occurring inside the browser to which a script can event occurs when the user clicks the mouse,submit a form, reset a form etc.

the event handler is javaScript code associated with a particular part of the document and a particular event. a handler is executed if and when the given event occurs.

registering event handlers

the javaScript event handling is single-threaded, so handlers are executed sequentially.

to assign events to html elements you can use event attribute.


        <htmlelement       event ="javascriptcode">  </htmlelement>
  <button   onclick = "alert('this is event_handler');">onclick click </button>
  <img src="newyear.jpg"   onmouseover="alert('the onmouseover event')" />

in this above example if the user click the button and mouse cursor over an image element then alert box will display.

assign events using dom-object

the html dom allows you to assign events to html elements using javaScript.


         document.getElementById('id_value').event= eventhandler
             <button   id="so" >please click this button</button>
             <button   id="dc" >please double click this button</button>
             function   show(){
                                        alert('this is click event');   }
  document.getElementById("so").onclick = show ;
  var   obj  = document.getElementById("dc");
         obj.ondblclick = new function("alert('this is double click event')");                       

event binding methods

the addeventlistener method registers an event handler for the specified event type.

note : this methods allow to assign multiple handlers to the same event on single object.


         object.addEventListener('event', handler, usecapture )
  • object : is the node to which the listener is to be bound
  • event : is the string indicating the event it is to listen for
  • handler: is the function that should be invoked when the event occurs
  • useCapture : is a boolean value indicating whether the handler should be invoked during the                      capture phase(true) or bubbling phase(false).
 function   show(){  document.getElementById('p').style.color= 'red' ; }
               <p id='p'> this is the first paragraph</p>
               <button id="b">click here</button>
                       var   obj = document.getElementById('b');
                              obj.addEventListener("click", show, true) ;
      </script>  </body>

the removeEventListener('event', handler, usecapture) method removes an event handler that the addEventListener method registered.