Understanding Events and Event Handlers

An event is something that happens when user interact with the web page, such as when he clicked a link or button, entered text into an input box or text area, made selection in a select box, pressed key on the keyboard, moved the mouse pointer, submits a form, etc. In some cases, the Browser itself can trigger the events, such as the page load and unload events.

When an event occur, you can use a JavaScript event handler (or an event listener) to detect them and perform specific task or set of tasks. By convention, the names for event handlers always begin with the word “on”, so an event handler for the click event is called onclick, similarly an event handler for the load event is called onload, event handler for the blur event is called onblur, and so on.

There are several ways to assign an event handler. The simplest way is to add them directly to the start tag of the HTML elements using the special event-handler attributes. For example, to assign a click handler for a button element, we can use onclick attribute, like this:

<button type="button" onclick="alert('Hello World!')">Click Me</button>

However, to keep the JavaScript seperate from HTML, you can set up the event handler in an external JavaScript file or within the <script> and </script> tags, like this:

<button type="button" id="myBtn">Click Me</button>
    function sayHello() {
        alert('Hello World!');
    document.getElementById("myBtn").onclick = sayHello;

Since HTML attributes are not case-sensitive, onclick may also be written as onClick, OnClick or ONCLICK. But its value is case-sensitive.

In general, the events can be categorized into four main groups — mouse events, keyboard events, form events and document/window events.