I have a button that already has an onclick-event and an assigned function. I wish to add another function call in front of it. I can imagine it should be possible to fiddle around with the onclick attribute (attr
), but I do not think this is best practice.
What would you consider best practice to prepend a function call on an existing onclick-event?
The prepend() method inserts specified content at the beginning of the selected elements. Tip: To insert content at the end of the selected elements, use the append() method.
To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.
If you are not afraid to mess with the guts of jQuery:
// "prepend event" functionality as a jQuery plugin
$.fn.extend({
prependEvent: function (event, handler) {
return this.each(function () {
var events = $(this).data("events"),
currentHandler;
if (events && events[event].length > 0) {
currentHandler = events[event][0].handler;
events[event][0].handler = function () {
handler.apply(this, arguments);
currentHandler.apply(this, arguments);
}
}
});
}
});
$("#someElement").prependEvent("click", function () {
whatever();
});
See it live: http://jsfiddle.net/Tomalak/JtY7H/1/
Note that there must already be a currentHandler
or the function will not do anything.
Disclaimer: I consider this a hack. It depends on jQuery internals that might change in the next version of the library. It works now (I tested jQuery 1.7.2), but don't be surprised if it breaks with a future version of jQuery.
I've written a short example here:
$("button").click(function() { // this is already existing
if ($("span").length) {
alert("ok");
}
});
var clicks = $("button").data("events").click.slice();
$("button")
.unbind("click")
.click(function() { // this is the new one which should be prepended
$("body").append($("<span>"));
});
$.each(clicks, function(i, v) {
$("button").click(v);
});
I don't think there's a way to prepend a function call on an existing onclick event, however you can try this:
$('#foo').unbind('click');
$('#foo').click(function() {
// do new function call..
// call original function again...
});
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With