Felix Eve
Felix Eve

Reputation: 3864

Trigger all jQuery events bound to an element

I have attached a click handler to a div that surrounds my radio inputs. When the div is clicked it sets the checked state of the radio, however I would also like to trigger all events bound to that radio. There could be multiple modules that bind to it, and they could potentially be binding on blur, change, click, dblclick, focus, hover etc.

Now I could use the following code:

$('.form-type-radio').click(function(){
    $(this).find('input').attr('checked', 'checked').trigger('blur').trigger('change').trigger('click').trigger('dblclick').trigger('focus').trigger('hover');
});

But really I would like a more succinct method - .trigger('all') would be perfect.

Is there a way to do this?

Upvotes: 2

Views: 6489

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

Or you could do it like that to:

DEMO jsFiddle

 $('.form-type-radio').click(function (e) {
     if(e.target != this) return;
     var input = $(this).find('input')[0],
         inputEvents = $._data(input, 'events');
     $.each(inputEvents, function (k, o) {
         $(input).triggerHandler(k);
     });
 });

If DIV contains more than just one input, use a for loop:

DEMO jsFiddle

$('.form-type-radio').click(function (e) {
     if (e.target != this) return;
     var inputs = $(this).find('input').get();
     for (var i = 0, z = inputs.length; i < z; i++) {
         var inputEvents = $._data(inputs[i], 'events');
         $.each(inputEvents, function (k, o) {
             $(inputs[i]).triggerHandler(k);
         });
     }
 });

NOTE: this will only works for events bound using jQuery.

Upvotes: 3

adeneo
adeneo

Reputation: 318232

Not something I would recommend, but maybe something like this

$.fn.triggerAll = function(exclude) {
    return this.each(function() {
        for (var key in this) {
            if (key.indexOf('on') === 0) {
                var ev = key.replace('on','');
                if ($.inArray(ev, exclude) == -1) {
                    $(this).trigger(ev);
                }
            }
        }
    });
};

used like

$('.form-type-radio').click(function(e){
    $(this).triggerAll(['click', 'mousedown']); // events not to trigger
});

FIDDLE

I added an option to pass an array of events to exclude to avoid recursion issues.

Upvotes: 3

Noquepoaqui
Noquepoaqui

Reputation: 395

I don't think there's a jQuery function to do that. a simple solution would be to add a new event to the object that would trigger all the other events. This way you have control on which events you are triggering but you don't have to trigger them every time. Something like:

$('input').on('all', function () {
    $(this)
        .trigger('blur')
        .trigger('change')
        .trigger('click')
        .trigger('dblclick')
        .trigger('focus')
        .trigger('hover');
});
$('input').trigger('all');

Upvotes: 1

Related Questions