Jcfg.J
Jcfg.J

Reputation: 101

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.

index.html:

<html>
<head>

    <h1>Hello there</h1>

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

</body>
</html>

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')) {
setUserName();
} else {
var storedName = localStorage.getItem('name');
myHeading.textContent = 'Mozilla is cool, ' + storedName;
}

myButton.onclick = function() {
setUserName();
}

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

Upvotes: 1

Views: 60

Answers (1)

sethreidnz
sethreidnz

Reputation: 655

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 jQuery you can use the $(document).ready() function

Upvotes: 1

Related Questions