this and $(this) in jQuery callbacks

What’s this and $(this) in jQuery callbacks? I’ve used them extensively, but never really paid attention to them until after I wrote the posts on what this is in JavaScript (part1 and part2). Now that I know how this works in JavaScript I got curious on how this is handled in jQuery and how $(this) is bound to the current element in jQuery event handler callbacks. The findings were not surprising, but rather show that jQuery is a well designed library.

Summary

The findings are simple:

  • this is a reference to the html DOM element that is the source of the event.
  • $(this) is a jQuery wrapper around that element that enables usage of jQuery methods.
  • jQuery calls the callback using apply() to bind this.
  • Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.

Let’s a have a look at how jQuery handles those cases internally.

jQuery UI Replacement for alert()

The Javascript alert(message) is a simple one-liner to show a message on a web page. It uses a standard system dialog box to display the message. On a site where most other UI elements are built using jQuery UI it is more natural to display the alerts in the same style. Unfortunately there is no built in one-liner for displaying a simple alert in jQuery UI, but it is easy to add an own one.


This is a standard jQuery UI dialog displayed using one line of code. It follows the same theme as the rest of the jQuery UI widgets used on the site and it behaves like a normal modal dialog. The code used for displaying the dialog is $.alert("message", "title"), which is a jQuery extension I added with a few lines of code.

Trying jQuery UI

The best way to learn a new technology is to try it out in a small sample project. With web development being my weak spot I decided to give jQuery UI a try. The only thing missing was the objectives of the sample project. I decided to try to make a small game for my 5 year old daughter. This also gave an opportunity to introduce my wife into software design and development. We wanted a game that doesn’t require reading, is free from ads and has no time restrictions.

The result is a simple math game.

Software Development is a Job – Coding is a Passion

I'm Anders Abel, a systems architect and developer working for Kentor in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

The complete code for all posts is available on GitHub.

Popular Posts

Archives

Series