I am trying to intercept the click of a button to do something before and after.
How to trigger the original click?
const el = document.querySelector(selector);
if (!el) { return; }
# Save original onclick
const onclick = el.onclick;
# Change onlick
el.onclick = async function (event) {
console.log('Before click');
# TODO: call the orignal onclick? <-------- ???
onclick.call(event);
console.log('After click');
}
I get the following output
BEFORE CLICK
Uncaught (in promise) TypeError: onclick is null
That is a little strange behavior. But I think you can use: onhover and onblur events.
https://www.w3schools.com/cssref/sel_hover.asp
Since you can only have one onclick handler at a time (when using Element.onclick), we just need to invoke the old function inside our new function. Here's the modified version of your code as you are likely intending:
var selector = ".blue";
window.onload = function() {
const el = document.querySelector(selector);
if (!el) {
return;
}
// Add an initial onclick to test
el.onclick = function(event) {
console.log("first onclick called");
};
// Save original onclick
const onclick = el.onclick;
// Change onlick
el.onclick = function(event) {
console.log('Before click');
// Call the orignal onclick
if (onclick !== null) {
onclick(event);
}
console.log('After click');
}
}
<div class="red">Red</div>
<div class="blue">Blue (click me)</div>
Also note, you can use EventTarget.addEventListener to add multiple eventListeners instead without needing to handle the old eventListener