Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

329
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda