Monday, December 16, 2013

Waiting for an Item to Exist Before Setting a jQuery Trigger

There are very elegant ways to do this.  This is not one of them.  This way works fine for me:

var checkExist = setInterval(function() {
    if(jQuery("#someid").length)  {
        jQuery("#someid").click( function() {
            // click handler code
        });
        clearInterval(checkExist);
    } 
}, 100);
All this does is set an interval to execute every 100 milliseconds.  It checks if the item exists (since the jQuery length function will return zero if it does not).  If it does exist, it adds the jQuery event handler and removes the interval.

Event Listeners in jQuery 1.8 (and Possibly Later)

To list all the event handlers on a jQuery selector using jQuery 1.8, use this in the JavaScript console:
$._data($('#yourid')[0], "events");
This also works as of the date of this writing on jQuery 1.9, but it might be disabled at some point.