JavaScript is a programming language that enables interactive web pages. It is commonly used to create dynamic content, control multimedia, animate images, and much more. You can include JavaScript in your HTML documents in several ways.
You can add JavaScript directly within an HTML element using the onclick
attribute or other event attributes. For example:
<button onclick="alert('Hello, world!')">Click Me</button>
JavaScript can be included directly in your HTML document using the <script>
tag placed within the <head>
or <body>
section. For example:
<script>
function showMessage() {
alert('Hello from internal JavaScript!');
}
</script>
<button onclick="showMessage()">Click Me</button>
For better organization, you can place JavaScript code in a separate file and link to it using the <script>
tag with the src
attribute. For example:
<script src="script.js"></script>
In the script.js
file:
function externalMessage() {
alert('Hello from external JavaScript!');
}
You can use JavaScript within HTML attributes to handle events. For example:
<input type="text" onkeyup="console.log('Key pressed: ' + this.value)">