Codes Explanation
How can JavaScript make a page interactive?
JavaScript is a programming language that runs in the browser. It can react to clicks, key presses and other events to make pages dynamic and interactive.
This page is for absolute beginners who already know a little HTML and CSS. First you build the structure with HTML, then you style it with CSS, and finally you use JavaScript to make the page respond to the user.
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.
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.
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.
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.