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:

<!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

JavaScript onclick event

Click the Click Me!!! Button to fire an event:

JavaScript onclick event output

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:

<!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

JavaScript ondblclick event

Click the Double Click Me!!! Button twice to fire an event:

JavaScript ondblclick event output

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:

<!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

JavaScript onmouseover event

Keep the mouse cursor on the button Keep the cursor here to fire an event:

JavaScript onmouseover event output

JavaScript Operators
JavaScript Objects
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment