0

I'm having issues using javascript to run a function. What I want to happen is I want the function to fire off when the user clicks a button. However, it fires off when the page loads.

Here is the entire code:

 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8"> 
<!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  </head>

 <body>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-2"></div>
            <div class="col-md-8">
                 <input type="submit" id="btn" value="Load">
                <div id="description">


          <div id="info">
            <h1 id="title"></h1>
            <p id="description"></p>
            <ul id="list"></ul>
          </div>
        </div>


            </div>
        <div class="col-md-2"></div>
    </div>
</div>


<script>

  var btn = document.getElementById('btn');

  var title = document.getElementById('title');
  var description = document.getElementById('description');
  var list = document.getElementById('list');


  btn.onclick = load();

  function load() {
    alert("Working.");
  }




</script>


  <!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Right now, it obviously doesn't do much except fire off an alert box. But I'll by using it to load in a file via XMLHttpRequest object later. But right now, its not working the way it should.

I should also point out that the code works fine with an anonymous function, But the whole idea is to have a normal function. I'm just not sure why it would work with an anonymous function and not a normal one.

Kaley36
  • 193
  • 6
  • 18

1 Answers1

0

It should be

var btn = document.getElementById('btn');
var title = document.getElementById('title');
var description = document.getElementById('description');
var list = document.getElementById('list');
btn.onclick = load;
function load() {
  alert("Working.");
}

DEMO

Sajeetharan
  • 186,121
  • 54
  • 283
  • 331