There are three main ways to add JavaScript to HTML:
1. Inline JavaScript
You can write JavaScript directly inside an HTML tag using the onclick
, onload
, or other event attributes:
<button onclick="alert('Hello!')">Click Me</button>
2. Internal JavaScript
You can place JavaScript inside a <script>
tag in your HTML file, usually in the <head>
or at the end of the <body>
:
<!DOCTYPE html> <html> <head> <title>Internal JS</title> <script> function sayHello() { alert('Hello from internal JS!'); } </script> </head> <body> <button onclick="sayHello()">Click</button> </body> </html>
3. External JavaScript
You can link to a separate JavaScript file using the src
attribute of the <script>
tag. This keeps your code cleaner.
<!DOCTYPE html>
<html>
<head>
<title>External JS</title>
<script src=”script.js”></script>
</head>
<body>
<button onclick=”sayHello()”>Click</button>
</body>
</html>
Description :
JavaScript can be added to HTML in three main ways, allowing developers to create interactive and dynamic web pages. Each method serves a different purpose depending on the structure, size, and complexity of your project.