Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
How to intercept click and do something before and after?

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
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

That is a little strange behavior. But I think you can use: onhover and onblur events. https://www.w3schools.com/cssref/sel_hover.asp

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!