ProgrammingFreak
ProgrammingFreak

Reputation: 35

Appending Button not working

function story1(){
var t=document.createElement('p');
t.innerHTML = "You wake up from your sleep in a half daze to hear noises of screams outside your bedroom window. You stumble over there to see what is the matter. You decide it's a good idea to grab your"+' <i onclick=addSword()> '+" sword "+' </i> '+"as you take the "+' <i onclick=story2()> '+" stairs. "+'</i>';
document.getElementById("story").appendChild(t);
}

function story2(){
var t = document.createElement('p');
t.innerHTML = "You realize that the door is locked and need to break the code in order to go outside." +' <i id="one" onclick=addOne()> '+ num1 +'</i>'+' <i id="two" onclick=addTwo()> '+ num2+'</i>'+' <i id="three" onclick=addThree()> '+ num3 +'</i>';
document.getElementById("story").appendChild(t);
var b = document.createElement('input');
b.type = 'button';
b.value = 'Check Code';
b.onclick = checkCode();
document.getElementById("story").appendChild(b);
}

In short these two functions are where my issue lies. I'm trying to append a button inside of a div to check to see if the code is broken. The coding for checkCode is working as is.

The issue is, that checkCode() is actually working when stairs in clicked instead of the button. I've tried b.on('click', checkCode()) and b.setAttribute('onclick', checkCode()).

Maybe I'm not coding the button right, but tutorials and reading answers to similar problems can only get me so far! (lol)

Thanks in advance!

Upvotes: 1

Views: 72

Answers (1)

PSL
PSL

Reputation: 123739

Your issue is that you are setting the result of the function checkCode to the handler/attribute in stead of the function reference. You are invoking it.

Try:

b.onclick = checkCode;

or

b.on('click', checkCode);

You need to set the reference of the function to the handler. setting it with () will invoke the function then and there and hence you see the behavior.

Upvotes: 1

Related Questions