Capturing Mouse Events
The onClick Event Handler
The onClick event handler can be applied to nearly all HTML elements visible on a page. One way we can implement it is to add one more attribute to the HTML element:
Let’s see an example; have a look at Listing 2.3.
Listing 2.3 Using the onClick Event Handler
<!DOCTYPE html> <html> <head> <title>onClick Demo</title> </head> <body> <input type=”button” onclick=”alert(You clicked the button!’)” value=”Click Me” /> </body> </html>
In this case, there’s just one statement:
alert(You clicked the button!’)
Figure 2.4 shows the result of clicking the button.
Figure 2.4 Using the onClick event handler
onMouseOver and onMouseOut Event Handlers
When we simply want to detect where the mouse pointer is on the screen with reference to a particular page element, onMouseOver and onMouseOut can help us to do that.
The onMouseOver event is fired when the user’s mouse cursor enters the region of the screen occupied by the element in question. The onMouseOut event, as I’m sure you’ve already guessed, is fired when the cursor leaves that same region.
Listing 2.4 provides a simple example of the onMouseOver event in action.
Listing 2.4 Using onMouseOver
<!DOCTYPE html> <html> <head> <title>onMouseOver Demo</title> </head> <body> <img src=”image1.png” alt=”image 1” onmouseover=”alert(You entered the image!’)” /> </body> </html>
The result of running the script is shown in Figure 2.5. Replacing onmouseover with onmouseout in the code will, of course, simply fire the event handler—and therefore pop up the alert dialog—as the mouse leaves the image, rather than doing so as it enters.
Figure 2.5 Using the onMouseOver event handler