Home > OS >  onclick event is triggered before an element is clicked
onclick event is triggered before an element is clicked

Time:10-18

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

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);
}

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related