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.

In small examples the <script> tag is often placed at the bottom of the <body>. In bigger projects, JavaScript is usually put in a separate file (for example script.js) and linked from the HTML page.

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.

4. What to do next?

Continue your JavaScript learning path

After you understand the basic idea of JavaScript, continue with these steps:

  • Practise more JavaScript: go to the JavaScript codes page and try the ready-made examples in the Sandbox.
  • Combine HTML, CSS and JavaScript: build a simple page with all three and make buttons, counters or small interactive elements.
  • Learn more from the blog: read posts on blog.playcode123.com about functions, event listeners and external JavaScript files.
  • Practise with assignments: open the HTML, CSS and JavaScript exercises (PDF) and try to create small interactive pages.

Remember: you do not need to understand everything at once. Take small steps, test your code in the Sandbox and learn by playing.