What is JavaScript example?
Table of Contents
Introduction
JavaScript is used to make websites interactive and dynamic by responding to user input, such as clicks or text entries. A basic example of JavaScript can show how this works on a web page. Let's explore a simple JavaScript example where a button changes text when clicked.
JavaScript Example: Button Click
HTML and JavaScript Code Example
In this example, when a user clicks a button, the text on the page will change.
How It Works:
- HTML Structure: The webpage contains a heading (
<h1>
) with the message "Hello, World!" and a button. - JavaScript Function: The
changeText()
function is triggered when the button is clicked. It changes the text inside the<h1>
element by accessing its ID (message
) and updating its content.
Result:
When the button is clicked, the message changes from "Hello, World!" to "You clicked the button!"
Conclusion
This simple example demonstrates how JavaScript can dynamically change content on a web page based on user interaction. By using JavaScript, developers can create more engaging and interactive experiences for users, such as changing text, showing alerts, or validating form input.