Learn Javascript and Global Events

 

You now know how to attach the various different event handlers to the various objects within your web page. Sometimes you will have multiple objects on the page where you want to attach the same event handler to run the same code.

This is easily done for two or three objects on your page but what do you do if you want an event handler attached to all of the objects on your page? If we create a global event handler then we can intercept all occurrences of one or more specified events throughout the entire web page without having to attach that event handler to any of the objects on our page.

The Global Handler

Let's start by looking at an example of a global event handler. The following code runs the kH() function whenever an onkeypress event occurs anywhere on your page. That function strips out any enter key presses so that your page effectively ignores the enter key.

function kH(e) {
var pK = e? e.which: window.event.keyCode;
return pK != 13;
}
document.onkeypress = kH;
if (document.layers)
document.captureEvents(Event.KEYPRESS);

The third last line of this code are what does most of the work of converting onkeypress (in this example) into a global handler. The first of these two lines identifies the event handler that we want to make global (onkeypress) and the function that we want to run when this event occurs (kH). The last two lines are specific to Netscape 4 which requires this extra code in order to capture the event and can be left off if you do not need to support that browser.

If you want to make more than one event handler operate globally you would replicate the third last line specifying the event handler and the function that it is to call. If you need to support Netscape 4 then you would also add the event into the end of the last line.

document.onkeypress = kH;
document.onclick = mD;
if (document.layers)
document.captureEvents(Event.KEYPRESS || Event.CLICK);

How the information associated with the event gets passed to the function (which key was pressed in our example) depends on which browser is being used. The example code tests for which browser is used as the first statement within the function in order to retrieve the ascii value of the key that was pressed from whichever of the two locations that the browser may have stored it in.

Using What You Know

You can now take any event handler that you have attached to a single object on any of your web pages and change it so that it can be triggered when the appropriate event occurs anywhere on your web page.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值