Triggering Event Handlers

Contact Us or call 1-877-932-8228
Triggering Event Handlers

Triggering Event Handlers

jQuery provides a way to trigger the event handlers attached to an element without any user interaction via the $.fn.trigger method. While this method has its uses, it should not be used simply to call a function that was attached as a click handler. Instead, you should store the function you want to call in a variable, and pass the variable name when you attach the event handler. Then, you can call the function itself whenever you want, without the need for $.fn.trigger.

Also, for the convenience methods, invoking them with no parameters triggers the event on the selected elements.

// A not-so-good practice
var foo = function(e) {
	console.log(e);
};
$('p').click(foo);
$('p').trigger('click');

// a better way - look for the event object
// if not present, means that call was not event-generated
var foo = function(e) {
	if (e) {
		console.log(e);
	} else {
		console.log('this didn\'t come from an event!');
	}
};
$('p').click(foo);
foo();
Next