|
|
|
|
|
Abstract: Coming up with something simple but useful to explain a concept is sometimes difficult. This week's article gives you an insight in a straight and simple manner into the event object and teaches you how you can use it in your pages. We will develop a page that opens up a new window and displays a help message whenever the user presses F2 key. "Why the F2 key?", you may ask. Actually F1 opens up the help of the browser and if you are using Internet Explorer there is no easy way to disable it. The article is filled with code, but the style is highly intutive and you will not need much explanation to understand it.
As you may have come to know by now, the event models of the two big browsers are very different. In fact, they are so different that writing cross browser code becomes almost impossible. Internet Explorer allows more combinations of events and objects as compared to Netscape Navigator. The onKeyDown event is supported by the body tag, which means we can fire a function whenever a key is pressed anywhere on the page. In the code that follows, we are defining a function with the name keyPressed. This function is associated with the onKeyDown event of the page. <html> <head> <script language="JavaScript1.2"> function keyPressed() { var F2 = 113; if (event.keyCode == F2) { var strMessage = "Hello, there. I will help you"; strMessage += " in understanding various parts of this page."; var strWindowProperties = "toolbar=no,location=no,status=no,"; strWindowProperties += "menubar=no,scrollbars=no,resizable=yes,"; strWindowProperties += "width=160,height=20"; var win = window.open (win, 'window', strWindowProperties); win.document.write (strMessage); } } </script> </head> <body onKeyDown="keyPressed()"> IE passes an event object implicitly to all the event handlers. One of the properties of the event object (for IE) is keyCode - Unicode of the key that was pressed when the event occurred. The code for F2 key is 113. Thus, our function, keyPressed, checks this property against the code of F2 and only then executes the lines that follow.
Netscape handles the concept in a slightly different manner. First of all, the event object must be received by the function as a parameter. Secondly, the property that gives the key pressed is called eventObject.which. Thirdly, the registering of the function is done in a slightly different manner as shown in the following code. The registration is done in two steps: (i) call the captureEvents method and (ii) set the event handler. Go To Page: 1 2
The copyright of the article Capturing Keys - Part I in JavaScript is owned by Muhammad Ali Shah. Permission to republish Capturing Keys - Part I in print or online must be granted by the author in writing.
|
|
|
|