Using the fireEvent() Method : HTML Body Event « HTML « JavaScript DHTML






Using the fireEvent() Method


/*
JavaScript Bible, Fourth Edition
by Danny Goodman 

John Wiley & Sons CopyRight 2001
*/

<HTML>
<HEAD>
<STYLE TYPE="text/css">
#mySPAN {font-style:italic}
</STYLE>
<SCRIPT LANGUAGE="JavaScript">
// assemble a couple event object properties

function getEventProps() {
    var msg = ""
    var elem = event.srcElement
    msg += "event.srcElement.tagName: " + elem.tagName + "\n"
    msg += "event.srcElement.id: " + elem.id + "\n"
    msg += "event button: " + event.button
    return msg
}
// onClick event handlers for body, myP, and mySPAN
function bodyClick() {
    var msg = "Click event processed in BODY\n\n"
    msg += getEventProps()
    alert(msg)
    checkCancelBubble()
}
function pClick() {
    var msg = "Click event processed in P\n\n"
    msg += getEventProps()
    alert(msg)
    checkCancelBubble()
}
function spanClick() {
    var msg = "Click event processed in SPAN\n\n"
    msg += getEventProps()
    alert(msg)
    checkCancelBubble()
}
// cancel event bubbling if check box is checked
function checkCancelBubble() {
    event.cancelBubble = document.controls.bubbleOn.checked
}
// assign onClick event handlers to three elements
function init() {
    document.body.onclick = bodyClick
    document.all.myP.onclick = pClick
    document.all.mySPAN.onclick = spanClick
}
// invoke fireEvent() on object whose ID is passed as parameter
function doFire(objID) {
    var newEvt = document.createEventObject()
    newEvt.button = 3
    document.all(objID).fireEvent("onclick", newEvt)
    // don't let button clicks bubble
    event.cancelBubble = true
}
</SCRIPT>
</HEAD>
<BODY ID="myBODY" onLoad="init()">
<H1>fireEvent() Method</H1>
<HR>
<P ID="myP">This is a paragraph <SPAN ID="mySPAN">(with a nested SPAN)</SPAN>
 that receives click events.</SPAN></P>
<HR>
<P><B>Control Panel</B></P>
<FORM NAME="controls">
<P><INPUT TYPE="checkbox" NAME="bubbleOn" onClick="event.cancelBubble=true">Cancel event bubbling.</P>
<P><INPUT TYPE="button" VALUE="Fire Click Event on BODY" onClick="doFire('myBODY')"></P>
<P><INPUT TYPE="button" VALUE="Fire Click Event on myP" onClick="doFire('myP')"></P>
<P><INPUT TYPE="button" VALUE="Fire Click Event on mySPAN" onClick="doFire('mySPAN')"></P>
</FORM>
</BODY>
</HTML>


           
       








Related examples in the same category

1. onBlur and onFocus Event Handlers
2.Using the onSelectStart Event Handler
3.Calling to Display the Alert Dialog onLoad
4.Calling to Display the Alert Dialog Directly
5.JavaScript Event Handlers :Loading/ Unloading a Document
6.Handling Load Events in a Content Document
7.Using Event Bubbling with the onClick Event
8. Running a Script from the onLoad Event Handler
9.Using addBehavior() and removeBehavior()