Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block inline onclick event and call it later in own click listener?

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>
like image 400
Black Avatar asked Jan 21 '26 10:01

Black


1 Answers

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.

like image 157
Rory McCrossan Avatar answered Jan 24 '26 01:01

Rory McCrossan