1

I want to make an extension method to jQuery so that it instead of looking like this:

$(document).on('click', '#myElement', function(e){
    doSomething(e);
});

looks like this:

$('#myElement').onClick(function(e) {
    doSomething(e);
})

This is because I want to be able to go the definition of '#myElement' when I click F12 in VS (I have the script file in a different folder).

I've tried with:

(function( $ ) {
    $.fn.onClick= function(callback) {

        if(callback)
        {
            $(document).on('click', $(this).attr('id'), callback.call(this));
        }
    });
})( jQuery );

But it doesn't seem to bind.

Joel Wiklund
  • 1,697
  • 2
  • 18
  • 24

1 Answers1

0

The following code should solve your problem:

(function($) {
  $.fn.onClick = function(callback) {
    $(this).on('click', callback)
  }
})(jQuery)

Try the following example:

Javascript / JQuery

(function($) {
  $.fn.onClick = function(callback) {
    $(this).on('click', callback)
  }
})(jQuery)

$(document).ready(function() {
  $("#myElement").onClick(function(e) {
    alert($(this).attr("id"))
  })
})

HTML

<div id="myElement">Test element</div>

EDIT

According to your comment you can use the following code but note, that the selector has to be an id.

(function($) {
  $.fn.onClick = function(callback) {
    $(document).on('click', "#" + $(this).attr("id"), callback)
  }
})(jQuery)

I tried a while to find the selector inside the extended function. In JQuery version 1.9 the selector field was removed and there is no official alternative.

https://stackoverflow.com/a/2421183/7111755

Note the official statement https://api.jquery.com/selector/. They suggest the following:

(function($) {
  $.onClick = function(selector, callback) {
    $(document).on('click', selector, callback)
  }
})(jQuery)

// Example
$(document).ready(function() {
  $.onClick("#myElement", function(e) {
    alert($(this).attr("id"))
  })
})

Let me know if it works and fits your needs.

Andre
  • 1,042
  • 12
  • 20
  • Hi! I need it to be on the form "$(document).on('click', ...", because I use partial views which don't bind if I use $("myId").on('click', ...". – Joel Wiklund Aug 27 '19 at 06:59
  • @xqtr I adjusted it. Hopefully it'll work. Have a nice day. – Andre Aug 27 '19 at 17:40