Jcfg.J Jcfg.J - 1 year ago 55
Javascript Question

onClick wont work in non-inlined javascript

So I am following a javascript demo from firefox (https://developer.mozilla.org/en-US/Learn/Getting_started_with_the_web/JavaScript_basics), and I practically copied and pasted the last demo on the site.



<h1>Hello there</h1>

<button>Change user</button>
<script src = "app.js"></script>


and app.js:

var myButton = document.querySelector('button');

var myHeading = document.querySelector('h1');

function setUserName() {
var myName = prompt('Please enter your name.');
localStorage.setItem('name', myName);
myHeading.textContent = 'Mozilla is cool, ' + myName;

if(!localStorage.getItem('name')) {
} else {
var storedName = localStorage.getItem('name');
myHeading.textContent = 'Mozilla is cool, ' + storedName;

myButton.onclick = function() {

I click the button on the webpage, but nothing happens... Any suggestions?

Answer Source

I suspect it is because your JavaScript element selecting and therefore the button event binding is executing before the DOM has loaded. You can use

document.addEventListener("DOMContentLoaded", function(event) { 
  // add all the JS here so that the DOM is loaded when you 
  // run your selector.

Or if you are going to use jQuer you can use the $(document).ready() function

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download