Home > OS >  Creating button in javascript, but onclick function automatic works
Creating button in javascript, but onclick function automatic works

Time:11-25

I am creating a button in javascript, but the onclick function apply to the button will automatically work even though I didn't click the button. Here is an example:

//Ignore the code will keep increasing buttons and other kinds. This is just an example I quickly made that similar to my actual code
function typing() {

  var btn = document.createElement('button')
  btn.innerHTML = "↓Show more";
  btn.id = "textbutton"

  function display() {
    btn.innerHTML = 'closed'
  }
  btn.onclick = display()
  document.body.appendChild(btn)
}
<textarea oninput="typing()"></textarea>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The innerHTML of the buttons in the above example created will automatically be closed even though I didn't click it.

Could anyone tell me why this happens and give me a better solution? Thanks for any responds!!!

CodePudding user response:

It's happening because of this line:

    btn.onclick = display()

That's taking the result of calling display() and setting it as the onclick handler for btn.

To fix it, just remove the parens:

    btn.onclick = display
  • Related