Embedding JavaScript in Webpages
JavaScript can be added to HTML pages in three main ways: inline, internal, and external.
Inline JavaScript
Inline JavaScript is written directly inside an HTML element using event attributes like onclick
.
<button onclick="alert('Hello!')">Click Me</button>
Internal JavaScript
Internal JavaScript is written inside a <script>
tag within the HTML file.
<!DOCTYPE html>
<html>
<head>
<title>Internal JS Example</title>
<script>
function greet() {
alert("Welcome!");
}
</script>
</head>
<body>
<button onclick="greet()">Greet Me</button>
</body>
</html>
External JavaScript
External JavaScript is stored in a separate .js
file and linked to the HTML using the src
attribute.
HTML (index.html
):
<!DOCTYPE html>
<html>
<head>
<title>External JS Example</title>
<script src="script.js"></script>
</head>
<body>
<button onclick="showMessage()">Click Me</button>
</body>
</html>
function showMessage() {
alert("Hello!");
}