Reputation: 25
I am trying to call a function twice in different functions. The first function creates two buttons and adds an onclick
event. I need to do this multiple times, but it's not working! Here's my Javascript:
// PLAYER INFO
var playerHP = 100;
var playerAt = 10;
var playerDef = 0;
var gold = 0;
//ENEMY FROG INFO
var enemy = 'FROG';
var enemyHP = 50;
var enemyAt = 5;
var loot = 5;
//FOF
function fof() {
var fight = document.createElement("BUTTON");
var t = document.createTextNode("FIGHT!");
fight.appendChild(t);
fight.id='attack';
document.body.appendChild(fight);
document.getElementById('attack').addEventListener('click', attack);
var or = document.createElement("P");
var g = document.createTextNode("or");
or.appendChild(g);
document.body.appendChild(or);
var flee = document.createElement("BUTTON");
var p = document.createTextNode("FLEE!");
flee.appendChild(p);
flee.id = 'flee';
document.body.appendChild(flee);
document.getElementById('playerflee').addEventListener('click', flee);
}
//ENEMY ATTACK
function enemyAttack() {
playerHP = playerHP - enemyAt;
var enemyFight = document.createElement('P');
var t = document.createTextNode('The enemy attacked you! You now have '+ playerHP + ' HP left!');
enemyFight.appendChild(t);
enemyFight.id = 'enemyattack';
document.body.appendChild(enemyFight);
fof();
}
//FIGHT
function attack() {
enemyHP = enemyHP - playerAt;
var playerAttack = document.createElement('P');
var t = document.createTextNode('You attacked the enemy! It has ' + enemyHP + ' HP left!');
playerAttack.appendChild(t);
playerAttack.id = 'attack';
document.body.appendChild(playerAttack);
enemyAttack();
}
//FLEE
function flee() {
var spare = document.createElement('P');
var t = document.createTextNode('You ran away! You gained 0 loot!');
spare.appendChild(t);
spare.id = 'playerflee';
document.body.appendChild(spare);
}
//Enemy Spawn
function spawn(){
var p = document.createElement("P");
var t = document.createTextNode("A wild FROG appeared! He has " + enemyHP + ' HP and ' + enemyAt+ ' attack! Will you...');
p.appendChild(t);
document.body.appendChild(p);
fof();
}
As you can see, I call fof()
twice- once in spawn()
and once in enemyAttack()
. I know it works in the first, as it works when I first call it then. However, when I come to the second, enemyAttack()
, it doesn't work! Any help would be appreciated.
Also, my HTML is just a button with an onclick
event calling spawn()
Upvotes: 0
Views: 1982
Reputation: 318182
ID's are unique, you can only have one single element in the document with any given ID. Knowing this, document.getElementById('attack')
only returns the first element in the DOM, every single time.
As you already have the element, there's no need to look it up
function fof() {
var fight = document.createElement("BUTTON");
var t = document.createTextNode("FIGHT!");
fight.className = 'attack';
fight.addEventListener('click', attack);
fight.appendChild(t);
document.body.appendChild(fight);
...
Upvotes: 2