A Platform To Learn To Code

JAVASCRIPT EVENTS



The events are the actions that happen to the HTMl elements in the document.

An event may occur either by browser or by user. Example

  • user click a button
  • browser finish loading the document
  • keyboard pressed
  • mouse moved
  • etc.

onclick event attached to button that create an alert box

When an event occurs like a button click in the above example, then we want to do something. Javascript can detect these events and can execute code on specified events.

HTML has an eventhandler attribute to be added to HTML elements that defines the type of we want to get from the element.

<element event="javascript code">content...</element>

Let's see an example of an onload event. onload event is triggered by the browser when the web page finishes loading.

Example

Run the code

Types of Events in Javascript

There are many different kinds of events in javascript. for example


window event

window events are the events that are generated when there is some change of any kind in the browser window.

Event Action Description
onload webpage loaded event is fired when page load is complete
unload closing page when user tried to close the page
resize resizing browser tab event is fired when page is resized

let's see examples.

Event - onload

Run the code

Event - onunload

Run the code

Event - onresize

Run the code

mouse event

Mouse events are the events that are triggered when there is any action taken by the mouse.

Event Action Description
mousedown/mouseup onmousedown/onmouseup mouse is clicked or released over an element
click onclick when mouse is clicked over an element
dbclick on double click when mouse is double clicked over an element
mousemove onmousemove when mouse is moved over an element

Let's see a few examples.

Event - mousedown/mouseup

Run the code

Output:

Click and release the mouse in the area below.


Event - click/dblclick

Run the code

Output:

Click and release the mouse in the area below.


keyboard event

keyboard events are the events that are generated when the keyboard button is clicked or released.

Event Action Description
onkeydown Button Down event is fired when any keyboard button is down
onkeyup Button released event is fired when any keyboard button is released
onkeypress Button pressed event is fired when any keyboard button is pressed

let's see examples.

Event - Keyboard

Run the code

Output:

Click and release button in area below.


form event

form events are the events that are generated when any action is taken on form elements.

Event Action Description
submit onsubmit event is fired when form is submitted
blur Focus Removed event is fired when focus is removed from input section
focus onfocus event is fired when cursor is focused on form
change onchange event is fired when form is changes

let's see examples.

form events

Run the code

Output:

Click and change values in form.



BOX