Event handling

One of the main usage of JavaScript is ‘event handling’. “Mouse click” and ‘pressing keys on keyboard’ are the example of ‘events’. With the help of JavaScript, we can perform certain actions at the occurrence of the events, as shown below.

  
            1 function alertMessage(message){ 
2 alert(message)
3 }

Note: ‘alert’ is used to display message in the ‘pop up’ window.

Example (HTML Code):

Consider the code below,

  • In Line 13, message ‘Hello’ is shown in the pop-up window on the event ‘onclick’. Note that “JavaScript:void(0)” is used here, which does not refresh the page.
  • Line 15 is same as Line 13, but “JavaScript:void(0)” is not used, therefore page will be refreshed.
  • Line 17 calls the function ‘alertMessage’ to display the mesage, which is defined in the above code.
  • Lines 19-25 use different events i.e. ‘onmouseover’, ‘onmouseleave’, ‘onmouseup’ and ‘onmousedown’; and the color and the text of the string changes based on these operations
  
	        1 <!-- js.html --> 
2
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <title>JavaScript</title>
7 </head>
8 <body>
9
10 <p id='p_name'></p>
11
12
13 <a href="JavaScript:void(0)", onclick="alert('Hello')">Say Hello</a><br> <!-- do not reload the page -->
14
15 <a href="", onclick="alert('Hello')">Say Bye</a><br> <!-- reload the page -->
16
17 <a href="JavaScript:void(0)", onclick="alertMessage('Bye via function')">Bye-function</a><br>
18
19 <a href="JavaScript:void(0)",
20 onmouseover="this.style.color='red'",
21 onmouseleave="this.style.color='blue'",
22 onmouseup="this.text='Not clicked'",
23 onmousedown="this.text='You clicked me'">
24 Not clicked
25 </a><br>
26
27
28 <!-- import JavaScript files here -->
29 <script src="asset/js/my_javascript.js"></script>
30
31 </body>
32 </html>

© Copyright 2025 | FolkLight Studios