I want to attach a click event handler to each and every (Button, Anchor, Select) on all pages in my application, and that handler should run before the already attached handlers declared in html like onclick="return SomeFunction('a','b');"
.
I found a question on stackoverflow for prepending handlers, and that was what I wanted exactly, the link to the question is:-
Jquery prepend click handler
But, the above code is not working, I doubt if it worked for the asker or not. The code I have written according to my requirements is:-
<input type="button" value="Click 1" onclick="f2();" />
$(document).ready(function() {
$("input[type=button]").each(function() {
// your button
var btn = $(this);
// original click handler
var clickhandler = btn.attr("onclick");
btn.attr("onclick", "return false;");
// new click handler
btn.click(function() {
alert('Prepended Handler');
clickhandler();
});
});
});
function f2() {
alert('Handler declared in HTML');
}
The output for this code should have been: An alert showing "Prepended Handler" and then a next alert showing "Handler declared in HTML".
But, the actual result is: Only the first alert is appearing and the second one is not.
Please tell me if you see any problem in this code.
And, how can this be done. ?
This should rearrange your click handlers.
$(document).ready(function() {
$("input[type=button]").each(function() {
// your button
var btn = $(this);
var clickhandler = this.onclick;
this.onclick = null;
// new click handler
btn.click(function() {
alert('Prepended Handler');
});
btn.click(clickhandler);
});
});
function f2() {
alert('Handler declared in HTML');
}
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