Event Object: Javascript

“Browser throws object automatically whenever an event occurs.” This is true with most browsers, except Microsoft’s Internet Explorer.
To solve the browser incompatibility and to make our programs work the same way in all major browsers(including Internet Explorer – IE ), we need to write the coding with little smartness!

What does this program do?
Here we will track the users cursor movement and display the X and Y axis of the cursor position in the browser window.
We will make use of onmousemove event and clientX and clientX properties.

We will also show how to catch the event objects and make proper use of them and how to handle a situation when the event object is not passed automatically.



YouTube Link: https://www.youtube.com/watch?v=UPqPooGsAHs [Watch the Video In Full Screen.]



HTML Code:
Here we have taken a form with two empty input tags. Latter with the help of javascript program we will fill the value of these empty input html tags.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
<html>
 <head>
  <title> Events In Javascript </title>
  <script type="text/javascript" src="event.js"></script>
 </head>
 <body>
 
  <form>
X axis: <input type="text" id="x"><br />
Y axis: <input type="text" id="y">
 
  </form>
 
 </body>
</html>

To link our html and the javascript files, we need to write this code in the head tag of html file:

   <script type="text/javascript" src="event.js"></script>

Javascript code:

1
2
3
4
5
6
7
8
9
10
11
12
 
document.onmousemove = call;
 
function call(evnt) {
 
if( !evnt )
evnt = window.event;
 
document.getElementById("x").value = evnt.clientX;
document.getElementById("y").value = evnt.clientY;
 
}

Here, when we move our mouse over the html document, call() function is invoked.
If the event object is not automatically passed by the browser i.e., if the browser is internet explorer, then we manually assign the event to evnt object using below code:

 
if( !evnt )
evnt = window.event;

With clientX and clientY property of the event object, we will assign the x axis and y axis value to the empty input tags using its id.