- Event Handling in JavaScript and jQuery
- Binding an Event Handler to an Event
- Binding Multiple Event Handlers
- Binding Event Handlers Using Shortcuts
- Calling Event Handlers Only Once
- Unbinding Event Handlers
- Using the Event Object
- Getting Mouse Coordinates
- Getting the Event Type
- Capturing Keystrokes
- Capturing Hover Events
- Getting Event Targets
Getting Mouse Coordinates
Mouse event objects come with built-in properties that let you determine exactly where the event occurred.
You can get the page coordinates—that is, the coordinates of the mouse event with respect to the upper-left corner of the client area (the area where the action takes place in a window, excluding toolbars, borders, the status bar, and so on) using the pageX and pageY properties. These properties are X and Y coordinates relative to the upper-left corner of the client area, which is location (0, 0).
You can also get the mouse location with respect to the upper-left corner of the screen using the screenX and screenY properties.
All coordinates are measured in pixels here.
To get a mouse event’s coordinates:
- Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example screenxy.html from the code for the book here.
- Enter the code to add the jQuery library and an <img> element and two <p> elements to the page (Script 4.11).
Script 4.11. Adding an <img> element and two <p> elements.
<html> <head> <title>Binding event handlers to events</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#target').bind('click', clicker); }); </script> </head> <body> <h1>Binding event handlers to events</h1> <h1>Click the flower...</h1> <img id="target" src="Image1.jpg"/> </body> </html>
- Add the code to display the screenX and screenY and the pageX and pageY coordinates when the mouse is clicked (Script 4.12).
Script 4.12. Displaying mouse coordinates.
<html> <head> <title>Getting mouse click coordinates</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#target').bind('click', clicker); }); function clicker(event) { $('#p1').text('(screenX, screenY) = (' + event.screenX + ', ' + event.screenY + ')'); $('#p2').text('(pageX, pageY) = (' + event.pageX + ', ' + event.pageY + ')'); } </script> </head> <body> <h1>Getting mouse click coordinates</h1> <h1>Click the flower...</h1> <img id="target" src="Image1.jpg"/> <p id="p1"></p> <p id="p2"></p> </body> </html>
- Save the file.
- Navigate to the file in your browser.
- Click the image, displaying the page and screen coordinates of the click event (Figure 4.6).
Figure 4.6 Getting mouse coordinates.