$(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 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.
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
- 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.
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.
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.