dwtutorials

Online

JavaScript - Events

JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. When the page loads, it is called an event. When the user clicks a button, that click too is an event. Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.

onclick Event Type

This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.

Example :-

Result

Click the following button and see result

onsubmit Event type

onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type.

Example :-

Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.

onmouseover and onmouseout

These two event types will help you create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element.

Example

HTML 5 Standard Events

The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript function to be executed against that event.

Attribute Value Description
Offline Script Triggers when the document goes offline
Onabort Script Triggers on an abort event
onafterprint Script Triggers after the document is printed
onbeforeonload Script Triggers before the document loads
onblur Script Triggers when the window loses focus
oncanplay Script Triggers when media can start play, but might has to stop for buffering
oncanplaythrought Script Triggers when media can be played to the end, without stopping for buffering
onchange Script Triggers when an element changes
onclick Script Triggers on a mouse click
ontextmenu Script Triggers when a context menu is triggered
oblclick Script Triggers before the document is printed
rag Script Triggers when an element is dragged
ragend Script Triggers at the end of a drag operation
ragenter Script Triggers when an element has been dragged to a valid drop target
ragleave Script Triggers when an element is being dragged over a valid drop target