Creating button in javascript, but onclick function automatic works

Advertisements

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>

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!!!

>Solution :

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

Leave a ReplyCancel reply