jQuery Namespacing with on() and off() method

With jQuery 1.7, jQuery team introduced 2 new ways to attach and remove events. on() method is used for attaching events to DOM elements, and off() method is used to removed event handlers. And you should use on() and off() only to attach and remove handlers, instead of bind(), live() and delegate().

Related Post:

There could be a situation where you have assigned multiple handlers on single event. For example,

$('#btnClick').on('click', func1());
$('#btnClick').on('click', func2());

Now, when trigger() is called on element, then both the function will get executed.

$('#btnClick').trigger('click'); // both functions will be called.

And when off() method will be called on element, both the functions will be removed.

$('#btnClick').off('click'); // both functions will be removed.

Now, what if when there are multiple handlers on single event and there is a need to call specific handler? In such situation, event namespacing is your friend.

Using event namespacing, at the time of creating event we can assign name. For example, "click.callFunc1" defines callFunc1 namespaces for this particular click event. Later on based on namespace, we can trigger or remove specific handler.

$('#btnClick').on('click.callFunc1', func1());
$('#btnClick').on('click.callFunc2', func2());

So to call func1() only, pass event.namespace in trigger() method.

$('#btnClick').trigger('click.callFunc1'); // Only func1() will be called.

And to remove specific function, pass event.namespace in off() method.

$('#btnClick').off('click.callFunc1'); // Only func1() will be removed.

You can also assign multiple namespaces together.

$('#btnClick').on('click.callFunc1.callFunc2', func1());

Feel free to contact me for any help related to jQuery, I will gladly help you.

Responsive Menu
Add more content here...