# first webpage with javascript

**URL:** <https://forum.kirupa.com/t/first-webpage-with-javascript/652416>\
**Category:** programming\
**Created:** [June 27, 2022, 5:34am UTC](https://forum.kirupa.com/t/first-webpage-with-javascript/652416 "2022-06-27T05:34:10Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![steve.mills](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/steve.mills/32/14961_2.png) [@steve.mills](https://forum.kirupa.com/u/steve.mills)\
**Post date:** [June 27, 2022, 1:32pm UTC](https://forum.kirupa.com/t/first-webpage-with-javascript/652416/2 "2022-06-27T13:32:26Z")

</div>

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.

```auto

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…

> [@Why does it work?](http://forum.kirupa.com/t/why-does-it-work/652382):
>
> let myButton = document.querySelector('#myButton'); myButton.addEventListener("click", doSomething, false); function doSomething(e) { alert('is this working?'); } Why the code works even if the “doSomething” function was defined after using it???

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.

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

```

---

_[View the full topic](https://forum.kirupa.com/t/first-webpage-with-javascript/652416)._
