first webpage with javascript

Hi Kirupa!

Just wondering why my function doesn’t display “hello world”. Do you know why?

Thank u!

let buttonElement = document.querySelector("button"); let textElement = document.querySelector('p'); buttonElement.addEventListener("click", changeText, false); const changeText =e=>{ textElement.innerText ="hello world!"; }

Hi Karies,

The first problem is that you are trying to access the function changeText before initialisation…

Which means that you need to declare your function first… then call it or add a listener using it…

e.g.


let buttonElement = document.querySelector("button");
let textElement = document.querySelector('p');
const changeText = e => { textElement.innerText = "hello world!"; }
buttonElement.addEventListener("click", changeText, false);

This is just good practice (most languages work this way)…

OR utilise hoisting…

Which works when using a function declaration…

The next problem you MAYBE have is that your JS will try to access a DOM element before it has been loaded on the page…

There are a 3 main ways to avoid this:

  • have an external script with defer e.g. <script src = "script.js" defer></script> (runs script after HTML has been parsed)

  • wrap all your eventListeners in a function and call the function when the DOM or <body> has loaded e.g. document.addEventListener("DOMContentLoaded", run) OR <body onload = "run()">

  • Embed the script element in the page after the elements you are targeting e.g.

<p>
<button>
<script style = "display: none">//my code</script>

Thank u Steve!
It works Just by switch the order of addEventListener to the bottom!

So the order matters right?

yeah if you’re not taking advantage of hoisting…