Do Not Trigger Real Event Names with jQuery! →

I post this link because I was writing some code earlier in the week and I was about to do exactly what this article tells us all not to do. Then I happened upon David Walsh’s article here and it actually led me to an even better solution than the one he suggests.

Until I read this I had no idea you could define your own custom events in jQuery and then trigger them later, but the winning solution is actually proposed by somebody in the comments section on David’s site: you can namespace your custom-named events. So:

$('#element').on('click.tabs', function() {

gets triggered when the element is actually clicked, or can be triggered programmatically with


the beauty here is that no other click events assigned to that element or its parents get triggered - we’re specifically targeting the namespaced event. If you’ve accidentally defined two .click() handling functions, or if there’s a .click() function on the parent element, the programmatic trigger doesn’t flow through to them.

Here’s a demo of what I’m talking about. Check out the difference between the three “trigger” links.

Comments & Discussion