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.