Javascript function print var in div

Trying to pass a variable to a function as a parameter of my function and have this function print the value of a global variable in a specific

var desc1 = "apple description";
var desc2 = "bananna description";
var desc3 = "orange description";

  function showDesc(arg) {
    var myDesc = arg;
    document.getElementById('description').innerHTML = myDesc; 
<div onclick="showDesc('desc1')">Apples</div>
<div onclick="showDesc('desc2')">Bannans</div>
<div onclick="showDesc('desc3')">Oranges</div>

<div id="description"></div>

Trying to make the value of desc1 show in when clicking on Apples, and show value of desc2 and likewise.

Currently, it is only printing "desc1" when clicking on "Apples" and "desc2" when clicking on "Bananas"

>Solution :

You are passing the ‘desc1’ and ‘desc2’ etc as strings into the function – you need to consider these as references. The easiest way is to create an object literal and use the passed in argument to select the chosen description from the object literal.

Also – you should be using buttons to handle the clicks –

const descriptions = {
  apple: "Apple description",
  banana: "Bananna description",
  orange: "Orange description"

  function showDesc(type) {
    document.getElementById('description').innerHTML = descriptions[type]; 
<button type="button" onclick="showDesc('apple')">Apples</button>
<button type="button" onclick="showDesc('banana')">Bannans</button>
<button type="button" onclick="showDesc('orange')">Oranges</button>


<div id="description"></div>

Leave a Reply