title: How do I prevent a JavasScript function from launching when the browser loads?
body: <p>So I created a function (onSuccess) that launches when an AJAX request is successful. The problem is that my function launches when my browser loads and I would only like for the function only to be called when a button with id myButton is clicked. I am locating my button using <code>document.getElementById("myButton");</code> but when I run <code>console.log(document.getElementById("myButton"));</code> in my browser console I get a Null result. </p>
  
  <p>I've looked around and gotten a few suggestions stating that my element wasn't in the DOM when my script ran. I can understand that but when I moved the location of my script and moved the <code>document.getElementById...</code> my script still doesn't work. I viewed a few suggestions on Stackoverflow but they were mostly JQuery solutions. I'm looking for a pure JavaScript solution. My  code is below</p>
  
  <p><a href="https://jsfiddle.net/jimmyt1001/yw26ncba/8/" rel="nofollow noreferrer">JSFiddle Example</a></p>
  
  <pre><code>            var el = document.getElementById("myButton");
              el.onclick = addUser("username", "email", onSuccess);
  
              function onSuccess(result){
                 alert ('successful');
              }
  
  
  
              // Do not modify this function. Add user service wrapper.
              function addUser(username, email, callback) {
                  var xhr = new XMLHttpRequest();
                  var response;
                  var success = (!!Math.round(Math.random()));
  
                  if (!success){
                      response = JSON.stringify({
                          success: success,
                          error: "Oups, something went wrong!"
                      });
                  } else {
                      response = JSON.stringify({
                          success: success,
                          user: {
                              username: username,
                              email: email
                          }
                      });   
                  }
  
                  xhr.open("POST", "/echo/json/");
                  xhr.onload = function () {
                          if (xhr.status === 200) {
                              callback(JSON.parse(xhr.responseText));
                      }
                  }
                  xhr.send("json=" + response);
              };
  </code></pre>