-1

In my cases when I want to use jQuery event such as click, change, mouseenter etc I need to use $(document).on('click', '.target_class'...

Normally we can simply use:

$('.target_class').on('click', function (e) {
    console.log('clicked')
});

In my cases I need to use:

$(document).on('click', '.target_class', function (e) {
    console.log('clicked')
});

That's why I need to create a small jQuery plugin to simplify the $(document).on, for example will become like this:

$('.target_class').myPlugin('click', function (e) {
    console.log('clicked')
});

I try with the following code with no luck :(

(function ($) {

    $.fn.myPlugin = function (event, callback) {

        return this.each(function () {

            $(document).find(this).on(event, function (e) {

                return callback();

            });

        });

    };

})(jQuery);

Thank you very much for any help :)

Peter Chimp
  • 93
  • 1
  • 8
  • If you only support jQuery < v3.0, you can use `$(document).on(event, this.selector, callback); return this;`. See [Getting initial selector inside jquery plugin](https://stackoverflow.com/q/5477394/283366). Unfortunately, the `selector` property was removed in v3.0 – Phil May 15 '22 at 03:30

0 Answers0