1

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>

asked Aug 31, 2015 at 12:09
1
  • 1
    id in function caller is a string, or undefined in some browsers (in onclick attribute). Commented Aug 31, 2015 at 12:15

3 Answers 3

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"];

Fiddle

And an extra example with multiple elements (and using this versus id in the function call) :

Fiddle2

answered Aug 31, 2015 at 12:17
Sign up to request clarification or add additional context in comments.

Comments

0

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!

answered Aug 31, 2015 at 12:16

Comments

0

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>
answered Aug 31, 2015 at 12:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.