[Solved] How Do You Run the ENTIRE Javascript Page From An Button In HTML?


I’ve created an entry on JSBin suggesting many improvements to what you have now:

http://jsbin.com/epurul/3/edit

Visit the entry to test the code yourself. Here is the content, for convenience:

HTML:

<body>
  <button onclick="playGame()">Play Game</button>  
</body>

And JavaScript:

// Expose playGame as a top-level function so that it can be accessed in the
// onclick handler for the 'Play Game' button in your HTML.
window.playGame = function() {

  // I would generally recommend defining your functions before you use them.
  // (This is just a matter of taste, though.)
  function UCFL(string) {
    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
  }

  // Rather than capitalize name everywhere it is used, just do it once
  // and then use the result everywhere else.
  function getName(message) {
    return UCFL(prompt(message));
  }

  var name = getName('So what is your name?');

  // Don't repeat yourself:
  // If you're writing the same code in multiple places, try consolidating it
  // into one place.
  var nameAttempts = 0;
  while (!confirm('So your name is ' + name + '?') && ++nameAttempts < 3) {
    // Don't use 'var' again as your name variable is already declared.
    name = getName('Then what is your name?');
  }

  if (nameAttempts < 3) {
    alert('Good. Lets start the roleplay, Sir ' + name + '.');
  } else {
    alert("Oh, guess what? I do not even fucking care what your name is anymore. Let's just start...");
  }

};

0

solved How Do You Run the ENTIRE Javascript Page From An Button In HTML?