title: jQuery Global Variable
body: <p>Can someone explain me why this doesn't work: </p>
  
  <pre><code>$(function() { 
     var damg = $(".hidden").val();
  
      $("button").click(function() {
          alert(damg);
      });
  });
  </code></pre>
  
  <p>jsFiddle: <a href="http://jsfiddle.net/raFnT/" rel="nofollow">http://jsfiddle.net/raFnT/</a></p>
  
  <p>Is it good to use global variables? I've also read that it is a slower option than typing it every time?</p>
  
  <p>To explain in detail:</p>
  
  <p>I have this:</p>
  
  <pre><code>$("button").click(function() {
              alert(damg);
          });
  </code></pre>
  
  <p>and the damg is a value of the input: <code>var damg = $(".hidden").val();</code></p>
  
  <p><strong>When you type something in the input and THEN press the button, alert the value of that input</strong>.</p>
  
  <p>I could use </p>
  
  <pre><code>$("button").click(function() {
  var damg = $(".hidden").val();
                  alert(damg);
              });
  </code></pre>
  
  <p>but in one point that I will have 100 functions I will end up like this:</p>
  
  <pre><code>$("button1").click(function() {
      var damg = $(".hidden").val();
                      alert(damg);
                  });
  
  $("button2").click(function() {
      var damg = $(".hidden").val();
                      alert(damg);
                  });
  
  $("button3").click(function() {
      var damg = $(".hidden").val();
                      alert(damg);
                  });
  
  $("button4").click(function() {
      var damg = $(".hidden").val();
                      alert(damg);
                  });
  
  $("button5").click(function() {
      var damg = $(".hidden").val();
                      alert(damg);
                  });
  </code></pre>
  
  <p>I want to set a global variable so that on every function I don't need to call the function again.</p>
  
  <p>Something like this:</p>
  
  <pre><code>var damg = $(".hidden").val();
  
  $("button1").click(function() {
          alert(damg);
      });
  
  $("button2").click(function() {
          alert(damg);
      });
  
  $("button3").click(function() {
          alert(damg);
      });
  
  $("button").click(function() {
          alert(damg);
      });
  
  $("button4").click(function() {
          alert(damg);
      });
  
  $("button5").click(function() {
          alert(damg);
      });
  </code></pre>