
Add JavaScript to HTML
To add JavaScript code to an HTML document, you can use the <script>
element. The <script>
element is used to embed or reference JavaScript code within an HTML page.
Here are a few ways to add JavaScript to an HTML document:
- Inline JavaScript:
<script>
// JavaScript code here
alert("Hello, World!");
</script>
In this example, the JavaScript code is directly placed between the opening and closing <script>
tags. When the HTML document is loaded, the JavaScript code will be executed.
- External JavaScript file:
<script src="script.js"></script>
In this case, the JavaScript code is placed in an external file called “script.js”. The src
attribute of the <script>
element is used to specify the path to the JavaScript file. By linking the external file, the JavaScript code will be executed when the HTML document is loaded.
- Event-driven JavaScript:
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
// JavaScript code here
alert("Button clicked!");
}
</script>
In this example, the JavaScript code is associated with the onclick
event of a button element. When the button is clicked, the myFunction()
function will be called, and the JavaScript code within the function will be executed.
Remember to place your JavaScript code within the appropriate <script>
tags in the HTML document. You can place the <script>
element in the <head>
section or at the end of the <body>
section, just before the closing </body>
tag.
By adding JavaScript code to your HTML document, you can enhance interactivity, manipulate the HTML elements, handle events, and perform various other dynamic operations on the web page.