3

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>

2
  • So, you are looking to change the precedence? Commented Aug 7, 2019 at 10:04
  • I try to execute some code before the onclick code is getting called, so yes, in other words, the precedence should be swapped. Commented Aug 7, 2019 at 10:05

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Does it also work with jQuery btw? I tried var originalInlineClickHandler = jQuery("#test").onclick; but it does not work. It says: Uncaught TypeError: originalInlineClickHandler is not a function
Not like that as jQuery doesn't have an onclick property. You could use $('#test')[0].onclick instead, though.
1

You could have an event for hover or mouseDown, but neither of those promise that there will be a click event. If you want to delete the inline onclick completely, you can unset it on the element in one of these events with something like element.onclick = null;.

2 Comments

It does not answer my question sorry
I agree that it doesn't fully answer the question, but it doesn't give you a way to access the button before it's clicked. How you want to save the value to click that button later is more dependent on your app. Regardless, I hope the other answer works better for you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.