JavaScript Events

HTML events are “things” that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can “react” on these events.

Focus Events:

  • focus: The focus event is fired when an element has received focus.
  • blur: The blur event is fired when an element has lost focus.

Example:

HTML Code:

<form id='form'>

<input type="text" placeholder="text input">
<input type="password" placeholder="password">

</form>

Javascript Code:

var form = document.getElementById('form');
if (form) {

form.addEventListener('focus', function (event) {
event.target.style.background = 'yellow';
}, true);

form.addEventListener('blur', function (event) {
event.target.style.background = 'none';
}, true)

}

Try it yourself:

Form Events:

  • reset: Event fires when the reset button is pressed
  • submit: Event fires when the submit button is pressed

Example:

HTML Code:

<form id='form'>

<input type="text" placeholder="username">
<input type="password" placeholder="password">
<input type="reset" placeholder="Reset form">
<input type="submit" placeholder="Submit form">

</form>

Javascript Code:

var form = document.getElementById('form');

if (form) {

form.addEventListener('reset', function (event) {
alert('The form was reset')}, true);

form.addEventListener('submit', function (event) {
alert('The form was submitted')
}, true)

}

Try it yourself:

Keyboard Events:

  • keydown: Any key is pressed
  • keypress: ANY key except Shift, Fn, CapsLock is in pressed position. (Fired continously.)
  • keyup: Any key is released

HTML Code:

<form id='form'>

<input type="text" placeholder="text input">
<input type="password" placeholder="password">

</form>

Javascript Code:

var form = document.getElementById('form');
if (form) {

form.addEventListener('keydown', function (event) {
event.target.style.background = 'yellow';
}, true);

form.addEventListener('keyup', function (event) {
event.target.style.background = 'none';
}, true)

form.addEventListener('keypress', function (event) {
event.target.style.background = 'pink';
}, true)

}

Try it yourself: