Create Your First Interactive Button with JavaScript
With JavaScript, you can make something happen when someone clicks a button.
This makes your website interactive.
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Button</title>
</head>
<body>
<h1>My First Button with JavaScript</h1>
<p id=”text”>Click the button to change this text.</p>
<button onclick=”changeText()”>Click here</button>
<script>
function changeText() {
document.getElementById(“text”).innerHTML = “The text has changed!”;
}
</script>
</body>
</html>
Explanation
In this example, you see a button.
When you click the button, the function changeText() runs.
The function finds the element with the id text and changes its content.
What do you learn here?
- how a button works
- how onclick works
- how JavaScript can change text on a page
