JavaScript Events

In simple words, JavaScript event is an action which is performed on any HTML elements. JavaScript is used to process based on Events.

HTML Event

An HTML event is performed by either browser or by user’s action.

Below are some examples of HTML events

  • A web page loading is finished
  • Form input field value changed
  • A pointer moves over an HTML element
  • An HTML form is submitted

When event is happens, an user want to perform something.

JavaScript event allows you to execute JavaScript code when some event happens

HTML has event handler attributes for HTML elements, which is combine with JavaScript code.

Events can be placed within single quotes or double quotes.

With Single Quote

<HTML-element event-name='JavaScript code'><HTML-element>

With Double Quote

<HTML-element event-name="JavaScript code"><HTML-element>

In below example, an onclick attribute is added for button input element

<!DOCTYPE html>
<html>
<body>

<input type="button" name="clickme" value="Click me" onclick="alert('You just clicked on a button');"/>

<p id="demo"></p>

</body>
</html>

Download the code Run the code

In above example, when an input button is clicked, JavaScript code will show and alert with message.

this keyword can be used to refer current element within JavaScript event.

In below example, onclick event code will change the size of button

<!DOCTYPE html>
<html>
<body>

<input type="button" name="clickme" value="Click me to expand" onclick="this.style.padding='10px';" />

<p id="demo"></p>

</body>
</html>

Download the code Run the code

It is rare that JavaScript code is of single line. So it is more common code practice to defined a function for event

<!DOCTYPE html>
<html>
<body>

<input type="button" name="clickme" value="Click me to expand" onclick="changeButtonSize(this);" />

<script>
function changeButtonSize($this) {
	$this.style.padding="10px";
}

</script>
<p id="demo"></p>

</body>
</html>

Download the code Run the code

Common HTML events list

Event       Description
onchange    An HTML element value has been changed
onclick     When an HTML element has been clicked
onmouseover When user moves the mouse over an HTML element
onmouseout  When user moves the mouse out of an HTML element
onkeydown   When user presses a keyboard key
onload      When the browser completes loading the page

There are many more events available in HTML and the list is much longer

What can JavaScript Events Do?

JavaScript events can be used to validate and handle user input, user’s actions and browser’s action:

  • To validate user input in forms
  • To do some action when page load finished
  • To do some action when page is closed
  • Change page content on user action
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .