0

I'm trying to make a script that creates a button with an onclick function; but when I make the code and run it, the onclick function that should be added to the newly created button gets placed onto the button I used to create the new button with. (The idea is that the first button in the end gets replaced with a document.load function but currently this is easier for testing to make sure it shows up where I want it.)

I'm a bit stuck as to why it places the "hideElement" function on the wrong button.

The current code is have:

function makeButton(){
  var newB = document.createElement('button');
  newB.innerHTML = 'Hide';
  newB.onclick = hideElement();

  var y = document.getElementsByClassName("element")[0];

  y.insertAdjacentElement('afterend', newB);
}

function hideElement(){
  var y = document.getElementsByClassName("element")[0];

  if (y.style.display === "none") {
    y.style.display = "block";
  } else {
    y.style.display = "none";
  }
}
<div class="element">
<strong>Blablabla</strong>
</div>
<p></p>
<button onclick=makeButton();>Create</button>

Thanks in advance for helping my tiny brain comprehend this issue.

Reyno
  • 6,119
  • 18
  • 27
  • Yes and no, it also does that, but that isn't really much of an issue (more of an inconvience). The really issue remains that it places the onclick function on the wrong element... But that link does solve that problem so thanks for that! – Jurgen Rutten Nov 24 '20 at 08:53
  • hold up; this solves it! I don't know why but jeeej! – Jurgen Rutten Nov 24 '20 at 08:54
  • `newB.onclick = hideElement();` _calls_ `hideElement` and stores `undefined` (which is implicitly returned by that function call) to `onclick`. Calling that function hides that element so it only _appears_ as if it is placed on top of it. – Ivar Nov 24 '20 at 08:56
  • How to I mark as solved? – Jurgen Rutten Nov 24 '20 at 09:00
  • You don't have to mark questions as solved. You already accepted the proposed duplicate so you can leave it as is. – Ivar Nov 24 '20 at 09:01

0 Answers0