In your second script you can read which function was bound to the click event by the first script. Then you can detach that handler and add your own, where you can (if you want) add the execution of the original function in the last step:
// script 1 ///////////////////////////////////////////////////////////
function f1() {
console.log('f1: function bound by script 1');
}
$('body').on('click', '#button', f1);
// script 2 ///////////////////////////////////////////////////////////
function f2() {
console.log('f2: my own function that should run first');
}
var original_f = $._data(document.body, 'events').click[0].handler;
$('body').off('click', '#button').on('click', '#button', function () {
f2();
original_f();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Trigger handlers</button>
This makes use of $._data
, which is not part of the public API of jQuery. See this answer.
Remarks
The above solution assumes that
the site's script (the first script) uses jQuery event delegation on the body
element for the element #button
; as follows:
$('body').on('click', '#button', function1);
Note that there are other ways to attach event handlers, but this answer assumes that the first script does it like this (as you provided in the question). Of course, function1
can be any function, or even an anonymous, in-line function.
You have full control over the second script and can redefine the click handler you have defined in it.
You write in comments that you cannot access the function of the first script (function1
). But please realise that if JavaScript is able to execute it, there is no reason why you could not have access to it via JavaScript.
Furthermore, since you informed that the first script uses jQuery to attach their handler, also jQuery knows which function it is and can access it (how else could it execute it when a click event happens?).
The solution I provide above actually asks jQuery to provide you the reference to that function. And then you can execute it just like jQuery would do when a click event occurs.
Testing the presence of the handler
In order to verify that indeed the first script has set a handler in this way:
$('body').on('click', '#button', function1);
... and that is still there, you can use the following script for debugging:
// script 1 -- you don't need to enter this, it is for this snippet to work with.
function f1() {
console.log('f1: function bound by script 1');
}
$('body').on('click', '#button', f1);
// script 2 -- your code ///////////////////////////////////////////////////////////
var click_handlers = $._data(document.body, 'events').click;
console.log('Info on BODY click handlers that have been set via jQuery:\n',
JSON.stringify(click_handlers, null, 2));
console.log('First click handler is this function:\n', click_handlers[0].handler);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>