Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Help. addeventlistener of null

I have a login.js file which inputs the value name and another file with an index.js file with their different html file. my 'login.addEventListener' give an error of "cannot read property 'addEventListener' of null".

this is my login.js file

let name = '';
const login = document.querySelector('.logButton');


login.addEventListener('click', () =>{
  let name = document.querySelector('.name').value;
});

this is my index.js

const now = new Date();
const hour = now.getHours();
const morning = " ";
const night = " ";
const div = document.querySelector('.page_1_body');

function print(docu){
  div.innerHTML = "<h1> <a href = 'Page_2/page2.html'>" + docu +"</a>";
}

function dayrnight(name){
if ( hour <= 24 && hour < 18 ){
  const morning = "<h1> Good Day " + name + " !</h1>";
  print(morning);
} else {
  const night = "<h1>Good evening " + name + " !</h1>";
  print(night);
}
}



dayrnight(name);

What does the html look like?

Here's my html for login

<body>

    <div class = "loginPage">
    <input type = "text" placeholder= "Username" class = "name" ></input> <a href = "../index.html"><button class = "logButton"> Login</button></a>
    </div>
<script src="Login.js"></script>
</body>

and here's for the index.html

<body>
    <div class = "page_1_body">
    </div>
<script src="index.js"></script>
<script src = "Login_page/Login.js"></script>
</body>

Hope this can help to solve my problem. Thanks

1 Answer

you need to call your login.js first otherwise index.js can't access the globals from login.js