July 26, 2000 - The releaseCapture() Method | WebReference

July 26, 2000 - The releaseCapture() Method

Yehuda Shiran July 26, 2000
The releaseCapture() Method
Tips: July 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Usually, an object fires an event when the event occurs within its physical limits on the page. For example, if you specify an onmousemove event for a DIV element, the appropriate event handler kicks in only when the mouse moves inside the DIV box.

Sometimes, though, you want an object to capture events that occur within other objects. You can do it with the setCapture() method:

object.setCapture([flag]);

where flag is an optional parameter equal to either false (no capturing), or true (default).

Equally important is remembering to release the event capturing. For example, if you set a DIV element capture onclick event, your code will keep watching out for mouse clicks and will transfer control to that DIV element, not allowing you to click any browser button such as the file/close. You release event capturing as follows:

object.releaseCapture();

In a typical page, you would set the event capturing in the BODY tag:

<BODY onload="oCaptureDemo.setCapture()" onclick=fnSwitchCapture()>

The oCaptureDemo is the object that is set to capture events from outside its physical boundaries. This object is defined as follows:

<DIV ID="oCaptureDemo" STYLE="border:solid black 1px; background-color:tan; 
padding:5px; width:350" onmousemove="mouseX.value=event.x; mouseY.value=event.y;">

The event captured here is onmousemove. Notice in the BODY tag above that we define an event handler for the onclick event. We use the onclick event to turn on and off the event capturing. The function fnSwitchCapture() is responsible for that:

function fnSwitchCapture() {
  if (capture) {
    capture = false;
	document.releaseCapture();
  }
  else {
    capture = true;
	oCaptureDemo.setCapture();
  }
}

We turn off the event capturing by calling document.releaseCapture(). We turn it back on by calling document.setCapture(). This page demonstrates the above mechanism. The DIV element is designed to capture onmousemove events from the whole document. You can turn this capturing off and on by a mouse click.

Supported mouse events include onmousedown, onmouseup, onmousemove, onclick, ondblclick, onmouseover, and onmouseout. The srcElement property of the window's event object always returns the object that is positioned under the mouse rather than the object that has mouse capture. The following key events are unaffected by mouse capture, and fire as usual: onkeydown, onkeyup, and onkeypress.

For more on the event model, go to Column 9, The Navigator Event Model, Column 10, The Internet Explorer Event Model, and Column 11, The Cross Browser Event Model.