Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda