3

For some reason, any event listener functions won't work on my browser(chrome), but they work on code pen? I been at this for about 2 hours, any thoughts?

Code pen link: http://codepen.io/koushkilla/pen/JXLVBX

<header>
<script src="pleasegodhelpme.js"></script>
    <h1>Javascript Events</h1>
</header>
<main>
  <h4>Add Numbers:</h4>
  <p>
    <input id="num-one"> + <input id="num-two">
  </p>
  <p id="add-sum"></p>
</main>

JS- FIle:

var numOne = document.getElementById("num-one");
    var numTwo = document.getElementById("num-two");
    var addSum = document.getElementById("add-sum");

numOne.addEventListener("input", add);
numTwo.addEventListener("input", add);

function add() {
  var one = parseFloat(numOne.value) || 0;
  var two = parseFloat(numTwo.value) || 0;

  addSum.innerHTML = "your sum is: " + (one+two);
}
halfer
  • 18,701
  • 13
  • 79
  • 158
KoushKilla
  • 53
  • 8
  • Place your ` – Rayon Apr 15 '16 at 05:40
  • Thanks it works!, may you please explain why in codepen it works and not browser. It makes sense now why it works when you put the script on the bottom, its because script needs some values to run initially right? – KoushKilla Apr 15 '16 at 05:48
  • `DOM api` works well when `DOM(Document-Object-Model)` is ready. If your script is written in `head` without `window.onload` event, it will get executed before elements are prepared! – Rayon Apr 15 '16 at 05:49
  • For your [_reference_](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Rayon Apr 15 '16 at 05:53

1 Answers1

1

What happens is that your Javascript code is executed before the DOM has loaded. This means that you're making calls in the Javascript code to elements that don't exist yet.

The easiest way to solve this problem is to place your <script> tag just before the closing <body> tag. It's always good practice to place Javascript at the end of your page since it also increases loading times.

<body>
<header>
    <h1>Javascript Events</h1>
</header>
<main>
    <h4>Add Numbers:</h4>
    <p>
      <input id="num-one"> + <input id="num-two">
    </p>
    <p id="add-sum"></p>
</main>
<script src="pleasegodhelpme.js"></script>
</body>
Jasper Vergers
  • 813
  • 6
  • 16