How can I block the inline onclick event of a button and call the function defined in that onclick later in my own click listener?
I try to inject some code which should execute before the button's onclick code is getting called.
function doSomething(el) {
console.log("doSomething was called...");
}
jQuery("#test").click(function(e) {
e.preventDefault();
console.log("click listener called...");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="test" onclick="doSomething(this)">Submit</button>
You can get a reference to the original inline handler from the element through its onclick property, which you can then reset to null. Then you can call the original inline function from within your own jQuery event handler when required, something like this:
var test = document.getElementById('test');
var originalInlineClickHandler = test.onclick;
test.onclick = null;
function doSomething(el) {
console.log("doSomething was called...");
}
$(function() {
jQuery("#test").click(function(e) {
e.preventDefault();
console.log("click listener called...");
originalInlineClickHandler();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="test" onclick="doSomething(this)">Submit</button>
It should be noted that this is rather hacky. I'd strongly suggest removing the inline event handler from the HTML, if possible.
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