JS Assignment With or, and
Advanced JS Syntax
by David McClelland
HTML
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div>
<div>
Add swords...
<br/>
<button onclick="armory.addSword('Broadsword')">
Broadsword
</button>
</div>
<div>
<button onclick="armory.addSword('Katana')">
Katana
</button>
</div>
<div>
<button onclick="armory.addSword('Claymore')">
Claymore
</button>
</div>
<div>
<input type='text' id="kit" style="width:300px" value="Sword Kit" />
</div>
<div>
<button onclick="armory.toggleKnight();">
Are You a Knight?
</button>
</div>
<div>
<input type='text' id="isKnightText" style="width:200px" value="Knighthood" />
</div>
<div>
<button onclick="getWeapon('Katana')">
Current Sword
</button>
</div>
<div>
<input type='text' id="currSword" style="width:300px" value="Current Sword" />
</div>
</div>
JavaScript
var kit = document.getElementById("kit");
var isKnight = true;
var armory = {
addSword: function(sword) {
this.swords = this.swords || [];
this.swords.push(sword);
kit.value = this.swords;
},
retrieveSword: function(request) {
if (this.swords) {
return (this.swords.indexOf(request) >= 0) ?
checkOutSword(request)
// to have mulitple statements in one conditional, call a function
// this.swords.splice(this.swords.indexOf(request), 1)[0]
:
currSword.value = "No " + request + " found, baby!";
} else {
currSword.value = "No swords in armory.";
}
},
toggleKnight: function(){
isKnight = !isKnight;
isKnightText.value = "Knighthood: "+isKnight;
}
}
function checkOutSword(request) {
currSword.value = "current sword: " + request;
return armory.swords.splice(armory.swords.indexOf(request), 1)[0];
}
function getWeapon(request){
var weapon = isKnight && armory.retrieveSword('Katana');
}