0

I really don't see what the issue is here. I'm pretty sure I made no typo either.

var homeButton = document.getElementById("home");

homeButton.addEventListener("click", myFunction);

function myFunction() {
  alert('Hello');
}
<div id="nav">
  <a id="home" class="navbutton" href="#">Home</a>
  <a id="trending" class="navbutton" href="#">Trending</a>
  <a id="categories" class="navbutton" href="#">Categories</a>
  <a id="about" class="navbutton" href="#">About</a>
</div>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335

2 Answers2

0

HTML of the document must be rendered first, in order to refer to element in the document. So you cannot use getElementById, or other element selection methods, if you put JS in the begging of the file. So move your all the scripts into the bottom of the document.

Harun Diluka Heshan
  • 1,155
  • 2
  • 18
  • 30
-1

this code is should be like this.

window.onload=function(){
var homeButton = document.getElementById("home");
homeButton.addEventListener("click", myFunction);
}
function myFunction() {
  alert('Hello');
}
<div id="nav">
  <a id="home" class="navbutton" href="#">Home</a>
  <a id="trending" class="navbutton" href="#">Trending</a>
  <a id="categories" class="navbutton" href="#">Categories</a>
  <a id="about" class="navbutton" href="#">About</a>
</div>
Negi Rox
  • 3,828
  • 1
  • 11
  • 18