In simple words, JavaScript event is an action which is performed on any HTML elements. JavaScript is used to process based on Events.
An HTML event is performed by either browser or by user’s action.
Below are some examples of HTML events
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>
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>
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>
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
JavaScript events can be used to validate and handle user input, user’s actions and browser’s action: