[jQuery] Event Handling – Basics

The most important part of any UI programming is the event handling: what to catch and how to provide handlers. To make a web page dynamic and responsive, you need to understand jQuery’s event handling mechanism.

This post explains the jQuery’s basic event handling features. I will deal with more advanced features such as event bubbling or delegation in upcoming posts.

 

1. JavaScript Event Handling

JavaScript event handling requires that you need to mix JavaScript code with HTML elements.

<body onload="myJSFunction();">

jQuery lets you separate JavaScript code and HTML tags. You can register any event handlers in the script block.

 

2. Page Load

The “$(document).ready()event handler is the base-place to add any custom jQuery code.

It’s similar with the “window.onload” event but has subtle differences. The “window.onload” event fires when a document is completely downloaded. On the other hand, the “$(document).ready()is invoked as soon as the HTML DOM is ready for use. This means a page structure is completely known but all related files (such as images) might not have been downloaded yet.

The “$(document).ready()is always preferable to the “onload“. But be careful! Some attributes such as image height and width might not be available when the “$(document).ready()handler is running.

 

3. Short Syntax

jQuery provides shortcuts to define event handlers as a common task.

The event handler for the “ready” event of the “document” can be defined:

jQuery(document).ready( function() { ... } );

The factory function “jQuery()” can be shortened to “$()

$(document).ready( function() { ... } );

Now, the “documentis a default argument of the “$()function.

$().ready( function() { ... } );

Moreover, you can just pass a handler function directly to the “$()“. The “ready” event will be automatically assumed.

$( function() { ... } );

Personally, I prefer the second version because it clearly shows the target name and the event name. Moreover, you can use the arrow function (ES2015) to make it even clearer.


$(document).ready( () => {

});

 

4. Registering Event Handlers

Suppose you want to register a handler to the “click” event of a “div” element. You do not register the handler in the “<div>” element. You need to register the handler inside the “$(document).ready()” handler.

By doing so, your handler will be registered when the page is loaded.

 

5. Clicking and Double-Clicking

The “click” and “dblclick” events are used for these basic operations. You can provide a handler function as an argument.

<div id="clickDiv">Click Me</div>

To catch the click event:

$(document).ready(() => {
  $('#clickDiv').click(() => console.log('You clicked'));
});

To catch the double-click event:

$(document).ready(() => {
  $('#clickDiv').dblclick(() => console.log('You double-clicked'));
});

 

6. Catching Focus

When you click a control in a page with a mouse or press a tab key, the control gets focused. You can provide a handler when an element becomes focused.

<input id="text1" type="text" />
$(document).ready(() => {
  $('#text1').focus(() => console.log('The textbox got focus.'));
});

 

7. Keyboard Events

It would be really useful if we can figure out which key is pressed. There are several keyboard related events you can catch:

  • keydown: A key is pressed
  • keyup: A pressed key is released
  • keypress: A key is pressed and released

Confused? When you press a key and hold it, the “keydown” event is invoked. When you press a key and release it very quickly, the “keypress” takes place.

Now how can you know which key is pressed. The handler function has an argument for it. The “which” attribute of an event argument returns the key code.

<input type="text" id="text1" />
<div id="div1"></div>

You can use the “keypress” event to check which key is pressed.

$(document).ready(() => {
  $('#text1').keypress(e => {
    $('#div1').text(e.which + ' is pressed');
  });
});

 

8. Mouse Events

There are many mouse related events:

  • mousedown: The mouse button is pressed over an element
  • mouseenter: The mouse cursor enters an element (not a child element)
  • mouseleave: The mouse cursor leaves an element
  • mousemove: The mouse is moved
  • mouseout: The mouse cursor leaves an element
  • mouseover: The mouse cursor enters an element (including a child element)
  • mouseup: The mouse button is released.

The “mouseleave” event differs from “mouseout” in the way it handles event bubbling. The “mouseout” event handler is also triggered when the mouse cursor moved out of the inner element. The “mouseleave” event handler is only triggered when the mouse leaves the element it is bound to, not a descendant.

<img id="img1" src ="..." alt="My Test Image" /></pre>
<div id="div1"></div>
$(document).ready(() => {
  $('#img1').mouseover(() => {
    $('#div1').text('The mouse is over the image');
  });
  $('#img1').mouseleave(() => {
    $('#div1').text('The mouse is out of the image');
  });
});

 

8. Is That All?

Absolutely not. I just showed how you can use event handlers in a simple way. I also showed only simple event handlers. jQuery provides you with more complex events such as “hover” or “toggle“. I will deal with them in subsequent posts.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s