1. From static to dynamic

JavaScript reacts to user actions

With only HTML and CSS, the page does not change by itself. With JavaScript you can respond when a user clicks a button, types text or moves the mouse.

<button onclick="sayHello()">Click me</button>

<script>
  function sayHello() {
    alert("Hello from JavaScript!");
  }
</script>

Copy this example into the Sandbox, run the code and click the button to see the alert.

2. Working with the page (DOM)

JavaScript can change HTML and CSS

The browser represents the page as a tree of elements called the DOM (Document Object Model). JavaScript can find elements and change their text, style or attributes.

<p id="message">Original text</p>
<button onclick="changeText()">Change text</button>

<script>
  function changeText() {
    const paragraph = document.getElementById("message");
    paragraph.textContent = "The text is now changed!";
  }
</script>

Here JavaScript looks up the element with id="message" and updates its text when the button is clicked.

3. Practice

What can you try yourself?

  • Change the message text to your own sentence in the example above.
  • Add a second button that changes the background color of the page.
  • Create a simple counter that increases a number every time you click a button.

Start with small scripts, test them in the Sandbox and slowly add more ideas as you get comfortable.