Events in JavaScript

Events in Javascript are the interactions of user with dynamic elemetns on the website such and a button, input box, form, page loading or event mouse hover. We will be covering the all of the related events in this tutorial. We hope you have a basic understanding of HTML.

<!DOCTYPE html>
<html>
<head>
<script>
function some_function(){
	statement1;
	statement2;
}
</script>
</head>
<body>
<p id="para">This is a paragraph.</p>
<input id="input" />
<button type="button">Click Me!!</button>
</body>
</html>

This is the basic HTML template that we will be using throughtout this tutorial series. Some events will require the input box, other the button and some cases, we will use both of them. We wil me modifying the function only.

onclick Event

The event triggers when you click a button. Replace the button code and function with this new code.

function some_function(){
	alert("Button is clicked");
}
<button type="button" onclick="some_function">Click Me!!</button>

onfocus and onblur Event

The event triggers when you focus in a input field. Replace the input field and function with this new code.

function some_function(){
	document.getElementById('input').style.background = 'red';
}
function some_other_function(){
	document.getElementById('input').style.background = 'yellow';
}
<input id="input" onblur="some_other_function();" onfocus="some_function();"/>

Keypress Event

The event triggers when you focus in a input field and press some key. Replace the input field and function with this new code.

function some_function(data){
	 	
}
<input id="input" onkeypress="some_function(this);"/>

Mouse Events

The event triggers when you focus mouse pointer on the paragraph. Replace para and function with this new code.

function some_function(para){
	 	para.style.color='red'
}
function some_other_function(para){
		para.style.color='black'	
}
<p id="para" onmouseover="some_function(this)" onmouseout="some_other_function(this);">This is a paragraph.</p>

Onload Event

This event is attached to the body tag of the HTML. Once the body is loaded, the event listener perfroms the execution.

<body onload="alert('Loaded')">


Next > < Prev
Scroll to Top