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

328
Visualizações
onclick event is triggered before an element is clicked

This is the code that I have with onclick event listener.

function makeSizer(size) {
    alert(size)
    document.body.style.fontSize = size + 'px';
}

document.getElementById('size-12').onclick = makeSizer(14);
document.getElementById('size-14').onclick = makeSizer(16);
body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 12px;
}
    <p>Some paragraph text</p>

    <a href="#" id="size-12">12</a>
    <a href="#" id="size-14">14</a>

However, I have no idea why once browser is loaded, the clicked event is triggered immediately or before I actually click the link. Could you help me explain this.

One solution that I got is to use closure like below by returning a function. I wonder if you have any others?

function makeSizer(size) {
    return function (){
        alert(size)
    document.body.style.fontSize = size + 'px';
    }       
}

By the way, there may be a dulplicate here. However, I'm seeking more general explanation/discussion than debugging.

Thank you.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try this:

function makeSizer(size) {
    alert(size)
    document.body.style.fontSize = size + 'px';
}

document.getElementById('size-12').onclick = function() { 
  makeSizer(14);
}

document.getElementById('size-14').onclick = {
  makeSizer(16);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You are assigning the result returned by makeSizer(14) to the element's onclick attribute.

If you want makeSizer(14) to be called on click, wrap it in a function:

function makeSizer(size) {
  alert(size)
  document.body.style.fontSize = size + 'px';
}

document.getElementById('size-12').onclick = () => makeSizer(14);
document.getElementById('size-14').onclick = () => makeSizer(16);
body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 12px;
}
<p>Some paragraph text</p>

<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>

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