javascriptfunctioneventsonclickonload

Javascript onclick function being called on page load


I have a simple Javascript function to be called when a button on the page is clicked. But it is getting called as soon as the page loads. Can anyone please tell me what the problem here is?

The HTML is:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btn">ClicMe!</button>
    <div id="demo"></div>
    <script src="script.js"></script>
  </body>
</html>

While the 'script.js' file is as follows.

var url = "example.txt";

function loadDoc(url, cFunction) {
  var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      cFunction(this);
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}

function myFunction(xhttp) {
  document.getElementById("demo").innerHTML = xhttp.responseText;
}

var btn = document.getElementById("btn");
btn.onclick = loadDoc(url, myFunction);

Solution

  • The last line of your script is calling the function instead of assigning the handler to it. Since you have arguments that you want to call it with, you need to use something to bundle the arguments and function together for when it is called. If you replace the last line with the following, it should work:

    btn.onclick = loadDoc.bind(undefined, url, myFunction) // "this" value is not needed, so it is left undefined