24 Feb JavaScript Events
Events are the users’ actions, a web page can respond to, such as,
- Loading a page,
- Mouse click,
- Keystroke,
- Click on submit button,
- Pressing a key,
- Closing a window, etc.
In this lesson, we will learn how to work with JavaScript events.
JavaScript onclick event
This event fires when a user clicks the mouse. On the click of the left mouse button, an HTML element gets clicked i.e., a function gets called. The onclick attribute is used for this.
Let us see an example to implement the onclick event in JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <body> <h1>JavaScript onclick event</h1> <p>Click the below button to display the student name.</p> <p id="test"></p> <script> // We have passed one parameter to the function function demo_function(stname){ alert("Student Name = "+stname); } </script> <input type="button" onclick="demo_function('Amit')" value="Click Me!!!"/> </body> </html> |
Output
Click the Click Me!!! Button to fire an event:
JavaScript ondblclick event
This event fires when a user double-clicks the mouse. On the double-click of the left mouse button, an HTML element gets clicked twice. The ondblclick attribute is used for this.
Let us see an example. We have considered the same example discussed above. The attribute ondblclick is set for the double click event:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <body> <h1>JavaScript ondblclick event</h1> <p>Click the below button twice i.e. double click to display the student name.</p> <p id="test"></p> <script> // We have passed one parameter to the function function demo_function(stname){ alert("Student Name = "+stname); } </script> <input type="button" ondblclick="demo_function('Amit')" value="Double Click Me!!!"/> </body> </html> |
Output
Click the Double Click Me!!! Button twice to fire an event:
JavaScript onmouseover event
This event fires when the mouse pointer is kept over an HTML element. The onmouseover attribute is used for this. Let us see an example. We have considered the same example discussed above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <body> <h1>JavaScript onmouseover event</h1> <p>Keep the mouse cursor on the below button to display the student name.</p> <p id="test"></p> <script> // We have passed one parameter to the function function demo_function(stname){ alert("Student Name = "+stname); } </script> <input type="button" onmouseover="demo_function('Amit')" value="Keep the cursor here"/> </body> </html> |
Output
Keep the mouse cursor on the button Keep the cursor here to fire an event:
No Comments