onaslowcamel
onaslowcamel

Reputation: 11

Empty div not displaying JavaScript output? (... at least I think that's the issue)

I'm pretty new to coding & I also haven't practiced these languages in a while, so this might be a really dumb question. I'm trying to make a random generator using this tutorial, but I've run into some issues with finishing the project.

My JavaScript is

function generator() {

  var ideas = ["design it for meerkats", "make it twice as big and half as loud", "use the rainbow filter in photoshop", "design using sound", "must not have a conscious or unconscious gender bias", "make it appeal to dogs", "make it so it can be unmade"];

  var randomNumber1 = parseInt(Math.random() * ideas.length);

  var command = ideas[randomNumber1];

  //alert(command);

};


//generator();

 if(document.getElementById("result")){
 document.getElementById("placeholder").removeChild(document.getElementById("result"));
  }
  //A div element is created to show the generated name.
  //The Name is added as a textnode. Textnode is added to the placeholder.
  var element = document.createElement("div");
  element.setAttribute("id", "result");
  element.appendChild(document.createTextNode(command));
  document.getElementById("placeholder").appendChild(element);

and my HTML is

<body onload=”generator()”>
    <div id="generator">
        <div id="placeholder"></div>
        <input type="button" value="Click here!" onclick="generator()" />
    </div>

In the tutorial (and on the demo) the randomly generated text shows up in in the "placeholder" div. However, when I try to run the code the text never shows up, just the button, which does nothing when clicked. I've gone back over the tutorial a bunch of times & I feel like I must be missing something really obvious.

Upvotes: 1

Views: 56

Answers (1)

Musa
Musa

Reputation: 97707

The code that places the the text in the div is outside of the generator function. This is the function that is called when the button is clicked

function generator() {

  var ideas = ["design it for meerkats", "make it twice as big and half as loud", "use the rainbow filter in photoshop", "design using sound", "must not have a conscious or unconscious gender bias", "make it appeal to dogs", "make it so it can be unmade"];

  var randomNumber1 = parseInt(Math.random() * ideas.length);

  var command = ideas[randomNumber1];

  if(document.getElementById("result")){
   document.getElementById("placeholder").removeChild(document.getElementById("result"));
  }
  //A div element is created to show the generated name.
  //The Name is added as a textnode. Textnode is added to the placeholder.
  var element = document.createElement("div");
  element.setAttribute("id", "result");
  element.appendChild(document.createTextNode(command));
  document.getElementById("placeholder").appendChild(element);
}

Upvotes: 6

Related Questions