Viewing events attached to elements via JavaScript

If like myself, you often attach functions to elements using jQuery, for example:

$('.btnName').live('click', function() {
    //do something

There is a nice little browser extension that will show all the elements on the page with a little bubble outlining the attached events/functions.

It is written by Allan Jardine, and you can get it from http://www.sprymedia.co.uk/article/Visual+Event



JQuery – bind event to non existant element

We all have to bind events to elements:

    do some stuff

But, what if that element doesn’t exist yet? Well, you can use the “live” handler:

$('#link').live('click', function(){
    do some stuff

This will carry the event handler on and will match any future element that matches the selector.

More information can be found here: http://api.jquery.com/live/

Sorting a SELECT with JQuery

Just a simple function to sort an already populated list. Obviously it would be easier to sort before populating, but there are the odd occasion where this is more complicated than you thought.

Requirements : JQuery

var selectOptions = $("#selectId option");

Then, we just run the sort command on the options array – and this easily sorts the items.

selectOptions.sort(function(a, b) {
    if (a.text > b.text) {
        return 1;
    else if (a.text < b.text) {
        return -1;
    else {
        return 0

Then, at the end empty the select object and re-append the sorted options array


Note. I just found a problem with this. If you have already selected an option, that selection will be lost unless you save the selection value before sorting and replace it at the end:

var selectedOption = $('#selectId').val();

And then to restore it