Get click handler from element in JQuery
11,272
$(...).click
is the jQuery click()
method, not your event handler.
You can use an undocumented internal API to get the list of event handlers:
jQuery._data( elem, "events" );
Author by
mcottingham
Updated on June 05, 2022Comments
-
mcottingham almost 2 years
How can I get a reference to the click handler of an element in JQuery?
Here is what I am trying to do:
Store the click handler, Change the click handler for the next click, Restore the original click handler
var originalClick = $(settings.currentTarget).click; $(settings.currentTarget).off("click"); $(settings.currentTarget).click(function (e) { e.preventDefault(); settings.model.modal.close(); $(settings.currentTarget).off("click"); $(settings.currentTarget).click(originalClick); });
The above code works the first time, however, when I click on the element again it fails:
Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'on'
Update:
I now realize that this is a really bad design that I am trying to do. I have resolved this issue by maintaining a visibility boolean in my viewmodel, if it is true, don't re-open the modal. -
mcottingham almost 11 yearsUnfortunately that gives me the same thing. I think that what I need to do is get this new click handler to execute before the original one and stopPropagation, just not sure how to do that.
-
Panama Jack almost 11 yearsI don't think you're using .Off() correctly. Why are you trying to unbind something that you haven't bound yet? From the jQuery documentation
The off() method removes event handlers that were attached with .on().
The first time you call it, you never attached it with .on() first. You might be mixing things. -
Panama Jack almost 11 yearsCan you give more info on what you're trying to do? What is
settings.currentTarget
? Also I noticed you said you were using knockout.js. Any reason this part can't be done with jQuery? -
Felix Kling almost 11 yearsUsing
var originalClick = $(settings.currentTarget).click;
doesn't make sense.jQuery.fn.click
is a jQuery method, not an event handler. You cannot bind it as event handler. -
Panama Jack almost 11 years@FelixKling I know, that is what I told him. I think he used knockout or something to bind initially.