I want the JavaScript to find the item information depending on item you clicked on, instead of making a new function for each item.
I am trying to do this by passing id into the JavaScript function as an argument, but that can't find the variable/array.
When you run the code it outputs spikes in the console, but it doesn't work when trying find the array.z
I have also tried using value instead of id, but that just does the same.
JSFiddle: http://jsfiddle.net/b2h0bo29/
var withspike = document.getElementById('withspike');
var withid = document.getElementById('withid');
var spikes = {name:"Spikes", description:"Do not eat me.", damage:"500" };
function itemClicked(id) {
console.log(id);
document.getElementById('withspike').innerHTML = spikes["description"];
document.getElementById('withid').innerHTML = id["description"];
}
<style>
#spikes {
width: 100px;
height: 100px;
border-radius: 50px;
background-color: #FF0000;
}
</style>
<div id="withspike"></div>
<div id="withid"></div>
<div onclick="itemClicked(id)" id="spikes"></div>
3 Answers 3
You could put spikes (and future other elements) in a containing object, and use id to obtain it from there:
var elements = {
spikes:{name:"Spikes", description:"Do not eat me.", damage:"500" }
};
call
elements[id]["description"];
And an extra example with multiple elements (and using this versus id in the function call) :
Comments
you shoud use this, to pass the element itself, and traverse to the dom element that you want.
For example, with:
<div id="withspike"></div>
<div id="withid"></div>
<div onclick="itemClicked(this)" id="spikes"></div>
You could use this function:
function itemClicked(el) {
var id = el.previousSibling.innerHTML; // Get previous sibling
console.log(id);
}
Thanks!
Edit. Sorry, i used id, while i meant to use this!
Comments
It might be smart to avoid mixing HTML and JavaScript. You can do this:
<div id="spikes"></div>
<script>
var spikes = document.getElementById("spikes");
spikes.addEventListener("click", function () {
itemClicked(spikes);
});
</script>
idin function caller is a string, orundefinedin some browsers (inonclickattribute).