Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating button in javascript, but onclick function automatic works

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading